id
int64
0
877k
file_name
stringlengths
3
109
file_path
stringlengths
13
185
content
stringlengths
31
9.38M
size
int64
31
9.38M
language
stringclasses
1 value
extension
stringclasses
11 values
total_lines
int64
1
340k
avg_line_length
float64
2.18
149k
max_line_length
int64
7
2.22M
alphanum_fraction
float64
0
1
repo_name
stringlengths
6
66
repo_stars
int64
94
47.3k
repo_forks
int64
0
12k
repo_open_issues
int64
0
3.4k
repo_license
stringclasses
11 values
repo_extraction_date
stringclasses
197 values
exact_duplicates_redpajama
bool
2 classes
near_duplicates_redpajama
bool
2 classes
exact_duplicates_githubcode
bool
2 classes
exact_duplicates_stackv2
bool
1 class
exact_duplicates_stackv1
bool
2 classes
near_duplicates_githubcode
bool
2 classes
near_duplicates_stackv1
bool
2 classes
near_duplicates_stackv2
bool
1 class
1,540,854
math_functions.cpp
olegkapitonov_spiceAmp/src/math_functions.cpp
/* * Copyright (C) 2018-2020 Oleg Kapitonov * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * -------------------------------------------------------------------------- */ #include "math_functions.h" #include <QScopedPointer> #include <gsl/gsl_complex_math.h> #include <fftw3.h> #include <zita-resampler/resampler.h> void fft_convolver(float signal[], int signal_n_count, float impulse_response[], int ir_n_count) { int n_count; if (signal_n_count >= ir_n_count) { n_count = signal_n_count; } else { n_count = ir_n_count; } QVector<double> signal_double(n_count); for (int i = 0; i < signal_n_count; i++) { signal_double[i] = signal[i]; } for (int i = signal_n_count; i < n_count; i++) { signal_double[i] = 0.0; } QVector<s_fftw_complex> signal_spectrum(n_count / 2 + 1); fftw_plan p; p = fftw_plan_dft_r2c_1d(n_count, signal_double.data(), (double (*)[2])signal_spectrum.data(), FFTW_ESTIMATE); fftw_execute(p); fftw_destroy_plan(p); QVector<double> impulse_response_double(n_count); for (int i = 0; i < ir_n_count; i++) { impulse_response_double[i] = impulse_response[i]; } for (int i = ir_n_count; i < n_count; i++) { impulse_response_double[i] = 0.0; } QVector<s_fftw_complex> impulse_response_spectrum(n_count / 2 + 1); p = fftw_plan_dft_r2c_1d(n_count, impulse_response_double.data(), (double (*)[2])impulse_response_spectrum.data(), FFTW_ESTIMATE); fftw_execute(p); fftw_destroy_plan(p); for (int i = 0; i < n_count / 2 + 1; i++) { gsl_complex signal_A = gsl_complex_rect(signal_spectrum[i].real, signal_spectrum[i].imagine); gsl_complex impulse_response_A = gsl_complex_rect(impulse_response_spectrum[i].real, impulse_response_spectrum[i].imagine); gsl_complex result_A = gsl_complex_mul(signal_A, impulse_response_A); signal_spectrum[i].real = GSL_REAL(result_A); signal_spectrum[i].imagine = GSL_IMAG(result_A); } p = fftw_plan_dft_c2r_1d(n_count, (double (*)[2])signal_spectrum.data(), signal_double.data(), FFTW_ESTIMATE); fftw_execute(p); fftw_destroy_plan(p); for (int i = 0; i < signal_n_count; i++) { signal[i] = signal_double[i] / n_count; } } QVector<float> resample_vector(QVector<float> sourceBuffer, float sourceSamplerate, float targetSamplerate) { QVector<float> targetBuffer; if (sourceSamplerate == targetSamplerate) { targetBuffer = sourceBuffer; } else { float ratio = targetSamplerate/(float)sourceSamplerate; targetBuffer.resize(sourceBuffer.size() * ratio); QScopedPointer<Resampler> resampl(new Resampler()); resampl->setup(sourceSamplerate, targetSamplerate, 1, 48); int k = resampl->inpsize(); QVector<float> signalIn(sourceBuffer.size() + k/2 - 1 + k - 1); QVector<float> signalOut((int)((sourceBuffer.size() + k/2 - 1 + k - 1) * ratio)); // Create paddig before and after signal, needed for zita-resampler for (int i = 0; i < sourceBuffer.size() + k/2 - 1 + k - 1; i++) { signalIn[i] = 0.0; } for (int i = k/2 - 1; i < sourceBuffer.size() + k/2 - 1; i++) { signalIn[i] = sourceBuffer[i - k/2 + 1]; } resampl->inp_count = sourceBuffer.size() + k/2 - 1 + k - 1; resampl->out_count = (sourceBuffer.size() + k/2 - 1 + k - 1) * ratio; resampl->inp_data = signalIn.data(); resampl->out_data = signalOut.data(); resampl->process(); for (int i = 0; i < targetBuffer.size(); i++) { targetBuffer[i] = signalOut[i] / ratio; } } return targetBuffer; }
4,344
C++
.cpp
122
31.237705
88
0.6454
olegkapitonov/spiceAmp
30
4
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,855
processor_thread.cpp
olegkapitonov_spiceAmp/src/processor_thread.cpp
/* * Copyright (C) 2018-2020 Oleg Kapitonov * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * -------------------------------------------------------------------------- */ #include "processor_thread.h" #include "math_functions.h" #include <QFile> #include <QProcess> #include <QTextStream> #include <QStandardPaths> #include <QDir> #include <sndfile.h> #include <cmath> #include <gsl/gsl_complex_math.h> #include <gsl/gsl_multifit.h> #include <gsl/gsl_spline.h> ProcessorThread::ProcessorThread(QObject *parent) : QThread(parent) { setObjectName(QString::fromUtf8("processor")); } void ProcessorThread::run() { QString tempDirPath = QStandardPaths::writableLocation(QStandardPaths::TempLocation); QString tempSpiceAmpDirPath = tempDirPath + QString("/spiceAmp"); QDir tempDir(tempSpiceAmpDirPath); tempDir.removeRecursively(); QDir(tempDirPath).mkdir("spiceAmp"); try { if (!QFile(diFilename).exists()) { throw "DI file not found!"; } if ((!QFile(IRFilename).exists()) && (!withoutCabinet)) { throw "Cabinet Impulse Response file not found!"; } if (!QFile(spiceFilename).exists()) { throw "SPICE model file not found!"; } msg->setMessage("Preparing data for ngspice..."); SF_INFO sfinfo; SNDFILE *sndFile; sfinfo.format = 0; int inputSampleRate; float inputSignalDuration = 0.0; sndFile = sf_open(diFilename.toUtf8().constData(), SFM_READ, &sfinfo); if (sndFile == NULL) { throw "DI file not found or can not be opened!"; } inputSampleRate = sfinfo.samplerate; inputSignalDuration = (float)sfinfo.frames / (float)sfinfo.samplerate; QVector<float> tempBuffer(sfinfo.frames * sfinfo.channels); sf_readf_float(sndFile, tempBuffer.data(), sfinfo.frames); sf_close(sndFile); QVector<float> di(sfinfo.frames); for (int i = 0; i < sfinfo.frames * sfinfo.channels; i += sfinfo.channels) { float sumFrame = 0.0; if (sfinfo.channels > 1) { for (int j = 1; j < sfinfo.channels; j++) { sumFrame += tempBuffer[i + j]; } sumFrame /= sfinfo.channels - 1; di[i / sfinfo.channels] = sumFrame; } else { di[i] = tempBuffer[i]; } } di = resample_vector(di, inputSampleRate, 441000); double diPeak = 0.0; for (int i = 0; i < di.size(); i++) { if (fabs(di[i]) > diPeak) { diPeak = fabs(di[i]); } } diPeak /= diNormalize; for (int i = 0; i < di.size(); i++) { di[i] /= diPeak; } FILE *diDataFile = fopen(QString(tempDir.absolutePath() + "/inputvalues").toUtf8(), "w+t"); if (!diDataFile) { throw "Can not create data file for ngspice!"; } for (int i = 0; i < di.size(); i++) { double t = 1.0/441000.0 * i; setlocale(LC_NUMERIC, "POSIX"); fprintf(diDataFile, "%.10g %.10g\n", t, di[i]); } fclose(diDataFile); QFile q_spiceFile(spiceFilename); if (!q_spiceFile.exists()) { throw "SPICE model not found or can not be opened!"; } q_spiceFile.copy(QString(tempDir.absolutePath() + "/spice_model.cir").toUtf8()); FILE *spiceFile = fopen(QString(tempDir.absolutePath() + "/spice_model.cir").toUtf8(), "a+t"); if (!spiceFile) { throw "Can not copy SPICE model to temp dir!"; } fprintf(spiceFile, ".subckt input_signal 0 1\n" "a1 %%v([input]) filesrc\n" "R1 input 1 10\n" "R2 1 0 100000\n" ".model filesrc filesource (file=\"inputvalues\" amploffset=[0] amplscale=[1]\n" "+ timeoffset=0 timescale=1\n" "+ timerelative=false amplstep=false)\n" ".ends\n" "\n" "X1 0 Vin input_signal\n" "X2 0 Vin Vout guitar_amp\n" "\n" ".control\n" "save v(Vout)\n" "tran 2.26757e-05 %f 0 1e-5\n" "wrdata output.csv v(Vout)\n" ".endc\n" "\n", inputSignalDuration); fclose(spiceFile); QString program = "ngspice"; QStringList arguments; arguments << "-b" << "spice_model.cir"; QProcess *ngspiceProcess = new QProcess(); ngspiceProcess->setWorkingDirectory(tempDir.absolutePath()); ngspiceProcess->start(program, arguments); msg->setMessage("ngspice started, processing..."); ngspiceProcess->waitForFinished(-1); msg->setMessage("ngspice finished."); QVector<double> outputT; QVector<double> outputV; QFile outputFile(tempDir.absolutePath() + "/output.csv"); if(!outputFile.open(QIODevice::ReadOnly)) { throw "SPICE simulation failed!"; } QTextStream outputFileStream(&outputFile); while(!outputFileStream.atEnd()) { QString line = outputFileStream.readLine(); float t, V; sscanf(line.toUtf8().constData(), "%f %f", &t, &V); if (outputT.size() == 0) { outputT.append(t); outputV.append(V); } else if (t > outputT[outputT.size()-1]) { outputT.append(t); outputV.append(V); } } outputFile.close(); msg->setMessage("Resampling ngspice output data..."); gsl_interp_accel *acc = gsl_interp_accel_alloc(); gsl_spline *spline = gsl_spline_alloc(gsl_interp_cspline, outputT.size()); gsl_spline_init (spline, outputT.data(), outputV.data(), outputT.size()); QVector<float> output(floor(outputT[outputT.size() - 1] * 441000.0)); for (int i = 0; i < output.size(); i++) { float t = i / 441000.0; float V = gsl_spline_eval(spline, t, acc); output[i] = V; } gsl_spline_free (spline); gsl_interp_accel_free (acc); output = resample_vector(output, 441000, inputSampleRate); msg->setMessage("Applying cabinet impulse response..."); float dcOutput = 0.0; for (int i = 0; i < output.size(); i++) { dcOutput += output[i]; } dcOutput /= output.size(); for (int i = 0; i < output.size(); i++) { output[i] -= dcOutput; } QVector<float> outputL(output); QVector<float> outputR(output); if (!withoutCabinet) { QVector<float> IRL; QVector<float> IRR; int IRSampleRate; sfinfo.format = 0; sndFile = sf_open(IRFilename.toUtf8().constData(), SFM_READ, &sfinfo); if (sndFile == NULL) { throw "SPICE simulation failed!"; } IRSampleRate = sfinfo.samplerate; QVector<float> tempBuffer(sfinfo.frames * sfinfo.channels); sf_readf_float(sndFile, tempBuffer.data(), sfinfo.frames); sf_close(sndFile); IRL.resize(sfinfo.frames); IRR.resize(sfinfo.frames); for (int i = 0; i < sfinfo.frames * sfinfo.channels; i += sfinfo.channels) { float sumFrame = 0.0; if (sfinfo.channels > 1) { for (int j = 1; j < sfinfo.channels; j++) { sumFrame += tempBuffer[i + j]; } sumFrame /= sfinfo.channels - 1; IRL[i / sfinfo.channels] = tempBuffer[i]; IRR[i / sfinfo.channels] = sumFrame; } else { IRL[i] = tempBuffer[i]; IRR[i] = tempBuffer[i]; } } IRL = resample_vector(IRL, IRSampleRate, inputSampleRate); IRR = resample_vector(IRR, IRSampleRate, inputSampleRate); fft_convolver(outputL.data(), outputL.size(), IRL.data(), IRL.size()); fft_convolver(outputR.data(), outputR.size(), IRR.data(), IRR.size()); } float maxOutput = 0.0; for (int i = 0; i < outputL.size(); i++) { if (fabs(outputL[i]) > maxOutput) { maxOutput = fabs(outputL[i]); } if (fabs(outputR[i]) > maxOutput) { maxOutput = fabs(outputR[i]); } } maxOutput /= 0.8; for (int i = 0; i < outputL.size(); i++) { outputL[i] /= maxOutput; outputR[i] /= maxOutput; } sfinfo.format = SF_FORMAT_WAV | SF_FORMAT_PCM_16; sfinfo.frames = outputL.size(); sfinfo.samplerate = inputSampleRate; sfinfo.channels = 2; sfinfo.sections = 1; sfinfo.seekable = 1; SNDFILE *outputWavFile = sf_open(outputFilename.toUtf8().constData(), SFM_WRITE, &sfinfo); if (outputWavFile == NULL) { throw "SPICE simulation failed!"; } QVector<float> outTempBuffer(output.size() * 2); for (int i = 0; i < (outputL.size() * 2 - 1); i += 2) { outTempBuffer[i] = outputL[i / 2]; outTempBuffer[i + 1] = outputR[i / 2]; } sf_writef_float(outputWavFile, outTempBuffer.data(), output.size()); sf_close(outputWavFile); tempDir.removeRecursively(); emit processorSuccess(); } catch (char const* error) { tempDir.removeRecursively(); emit processorError(error); } }
9,577
C++
.cpp
296
26.324324
98
0.608582
olegkapitonov/spiceAmp
30
4
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,856
message_widget.h
olegkapitonov_spiceAmp/src/message_widget.h
/* * Copyright (C) 2018-2020 Oleg Kapitonov * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * -------------------------------------------------------------------------- */ #ifndef MESSAGE_WIDGET_H #define MESSAGE_WIDGET_H #include <QDialog> #include <QLabel> class MessageWidget : public QDialog { Q_OBJECT public: MessageWidget(QWidget *parent = nullptr); void setTitle(QString title); void setMessage(QString message); private: QLabel *messageLabel; }; #endif //MESSAGE_WIDGET_H
1,173
C++
.h
33
33.515152
80
0.718447
olegkapitonov/spiceAmp
30
4
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,857
mainwindow.h
olegkapitonov_spiceAmp/src/mainwindow.h
/* * Copyright (C) 2018-2020 Oleg Kapitonov * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * -------------------------------------------------------------------------- */ #ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QWidget> #include "ui_mainwindow.h" #include "processor_thread.h" #include "message_widget.h" class MainWindow : public QWidget { Q_OBJECT public: MainWindow(QWidget *parent); private: Ui::MainWindow ui; MessageWidget *statusBox; ProcessorThread *processor; void checkFilenames(); void saveLastPath(QString path); QString loadLastPath(); private slots: void on_exitButton_clicked(); void on_diButton_clicked(); void on_spiceButton_clicked(); void on_IRButton_clicked(); void on_normalizeSlider_valueChanged(int value); void on_processButton_clicked(); void on_withoutCabinetCheckBox_stateChanged(int state); void on_outputButton_clicked(); void on_processor_finished(); void on_processor_processorError(QString error); void on_processor_processorSuccess(); void on_diFilenameEdit_textEdited(QString); void on_spiceFilenameEdit_textEdited(QString); void on_IRFilenameEdit_textEdited(QString); void on_outputFilenameEdit_textEdited(QString); }; #endif //MAINWINDOW_H
1,922
C++
.h
54
33.222222
80
0.747442
olegkapitonov/spiceAmp
30
4
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,858
processor_thread.h
olegkapitonov_spiceAmp/src/processor_thread.h
/* * Copyright (C) 2018-2020 Oleg Kapitonov * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * -------------------------------------------------------------------------- */ #ifndef PROCESSOR_THREAD_H #define PROCESSOR_THREAD_H #include <QThread> #include "message_widget.h" class ProcessorThread : public QThread { Q_OBJECT void run() override; public: ProcessorThread(QObject *parent); QString diFilename; double diNormalize; QString spiceFilename; bool withoutCabinet; QString IRFilename; QString outputFilename; MessageWidget *msg; signals: void processorError(QString error); void processorSuccess(); }; #endif //PROCESSOR_THREAD_H
1,345
C++
.h
40
31.325
80
0.731066
olegkapitonov/spiceAmp
30
4
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,859
math_functions.h
olegkapitonov_spiceAmp/src/math_functions.h
/* * Copyright (C) 2018-2020 Oleg Kapitonov * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * -------------------------------------------------------------------------- */ #ifndef MATHFUNCTIONS_H #define MATHFUNCTIONS_H #include <QVector> struct s_fftw_complex { double real; double imagine; }; void fft_convolver(float signal[], int signal_n_count, float impulse_response[], int ir_n_count); QVector<float> resample_vector(QVector<float> sourceBuffer, float sourceSamplerate, float targetSamplerate); #endif
1,255
C++
.h
31
36.645161
97
0.688269
olegkapitonov/spiceAmp
30
4
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,860
wxMain.cpp
msrst_interactive-8051-disassembler/wxMain.cpp
/************************************************************************ * Copyright (C) 2020-2021 Matthias Rosenthal * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/> ***********************************************************************/ #include <cmath> #include "wx/config.h" #include "wx/textdlg.h" #include "wx/clipbrd.h" #include "wxMain.h" #include "utils/utils_wx.h" #include <boost/filesystem.hpp> // sadly, there is no function in scintilla to prevent user modifications, but allow // modifications by the program (SetReadOnly / SetEditable also prevent program's // modifications). Therefore, we need to set the textCtrl to editable on each possible // modification. class wxSTCEditableLocker { private: wxStyledTextCtrl *wxstc; public: wxSTCEditableLocker(wxStyledTextCtrl *wxstc) { this->wxstc = wxstc; wxstc->SetEditable(true); } ~wxSTCEditableLocker() { wxstc->SetEditable(false); } }; BEGIN_EVENT_TABLE(Dis8051Frame, wxFrame) EVT_CLOSE(Dis8051Frame::OnClose) EVT_MENU(idMenuQuit, Dis8051Frame::OnQuit) EVT_MENU(idMenuAbout, Dis8051Frame::OnAbout) EVT_MENU(idMenuSaveMetaFile, Dis8051Frame::OnSaveMetaFile) EVT_MENU(idMenuGoto, Dis8051Frame::OnGoto) EVT_MENU(idMenuFindPrevious, Dis8051Frame::OnFindBefore) EVT_MENU(idMenuFindNext, Dis8051Frame::OnFindNext) EVT_MENU(idMenuToggleCallAnnotation, Dis8051Frame::OnToggleCallAnnotation) EVT_MENU(idMenuReadAddressFromCode, Dis8051Frame::OnReadAddressFromCode) EVT_TIMER(idTimerUpdateUI, Dis8051Frame::OnTimerUpdateUI) EVT_STC_UPDATEUI(idDisassemblyTextCtrl, Dis8051Frame::OnDisassemblyTextUpdated) EVT_BUTTON(idButtonFindBefore, Dis8051Frame::OnFindBefore) EVT_BUTTON(idButtonFindNext, Dis8051Frame::OnFindNext) EVT_TEXT_ENTER(idTextCtrlComment, Dis8051Frame::OnCommentEnterPressed) EVT_TEXT_ENTER(idTextCtrlFunction, Dis8051Frame::OnFunctionEnterPressed) EVT_CHECKBOX(idCheckBoxFunctionShown, Dis8051Frame::OnToggleFunctionShown) EVT_BUTTON(idButtonDeleteFunction, Dis8051Frame::OnFunctionDelete) END_EVENT_TABLE() Dis8051Frame::Dis8051Frame(wxFrame *frame, const wxString& title, std::string firmwareFile, std::string metaFile, Dis8051App *app) : wxFrame(frame, -1, title), timer_gui_update1(this, idTimerUpdateUI) { m_app = app; gui_palette_init(c_gui_palette); this->firmwareFile = firmwareFile; this->metaFile = metaFile; c_logger.reset(new logger::logger); c_logger->LogInformation("started interactive 8051 disassembler, logging to log.txt"); c_logger->AddLogDisplay("log.txt"); disassembly = std::make_shared<disas8051::Disassembly>(c_logger.get()); std::string bufString; if(utils::GetFileString(firmwareFile, &bufString, true)) { c_logger->LogInformation("Loaded " + std::to_string(bufString.length()) + " bytes from " + firmwareFile); disassembly->buf = utils::StdStringToUstring(bufString); disas8051::Disassembler disassembler(c_logger.get()); if(disassembly->openMetaFile(metaFile) == 0) { c_logger->LogInformation("Loaded metadata file " + metaFile); } else { // create a new meta file disassembly->functions[0] = disas8051::Function{"start"}; c_logger->LogInformation("Created new meta, starting at address 0"); } c_logger->LogInformation("Disassembling..."); for(auto itFunction = disassembly->functions.begin(); itFunction != disassembly->functions.end(); itFunction++) { disassembler.followCodePath(disassembly->buf, itFunction->first, disassembly.get()); } c_logger->LogInformation("Resolving remapping calls..."); disassembly->resolveRemapCalls(&disassembler); c_logger->LogInformation("Resolving comments..."); disassembly->resolveComments(); c_logger->LogInformation("Resolving function ends addresses..."); disassembly->resolveFunctionEndAddresses(); c_logger->LogInformation("Auto commenting..."); disassembly->autoComment(); c_logger->LogInformation("Processed firmware + metadata file."); } else { c_logger->LogError("Could not open file " + firmwareFile); wxMessageBox(wxString::Format(wxT("Error: Could not open firmware file %s"), wxString::FromUTF8(firmwareFile.c_str()))); } // create a menu bar wxMenuBar* mbar = new wxMenuBar(); wxMenu* fileMenu = new wxMenu(_T("")); fileMenu->Append(idMenuSaveMetaFile, _("&Save metadata file\tCtrl-S")); fileMenu->AppendSeparator(); fileMenu->Append(idMenuGoto, _("&Goto line\tCtrl-G")); fileMenu->Append(idMenuFindNext, _("Find &next\tF3")); fileMenu->Append(idMenuFindPrevious, _("Find &previous\tShift-F3")); fileMenu->Append(idMenuToggleCallAnnotation, _("Toggle call annotation\tCtrl-K"), _("Toggle whether calling arrow from the current code to some function are displayed")); fileMenu->Append(idMenuReadAddressFromCode, _("Clipboard address from code\tCtrl-R"), _("Queries an address and copies the 2 bytes from this address to clipboard")); fileMenu->AppendSeparator(); fileMenu->Append(idMenuQuit, _("&Quit\tAlt-F4"), _("Quit the application")); mbar->Append(fileMenu, _("&File")); wxMenu* helpMenu = new wxMenu(_T("")); helpMenu->Append(idMenuAbout, _("&About\tF1"), _("Show info about this application")); mbar->Append(helpMenu, _("&Help")); SetMenuBar(mbar); wxBoxSizer* topSizer = new wxBoxSizer(wxVERTICAL); //wxPanel *panel_top = new wxPanel(this); wxNotebook *notebook = new wxNotebook(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxBK_DEFAULT); wxPanel *panel_disassembly = new wxPanel(notebook); notebook->AddPage(panel_disassembly, wxT("Disassembly"), false); wxBoxSizer *wxsz_panel_disassembly = new wxBoxSizer(wxHORIZONTAL); scroll_overview = new ScrollOverview(this, panel_disassembly, wxID_ANY); wxsz_panel_disassembly->Add(scroll_overview, 0, wxALL | wxEXPAND, 2); wxsw_main = new wxSplitterWindow(panel_disassembly, wxID_ANY); wxPanel *panel_left = new wxPanel(wxsw_main); wxBoxSizer *wxsz_left = new wxBoxSizer(wxVERTICAL); wxSplitterWindow *wxsw_disassembly = new wxSplitterWindow(panel_left, wxID_ANY); annotation_canvas = new AnnotationCanvas(this, wxsw_disassembly, wxID_ANY); wxrt_disassembly = new wxStyledTextCtrl(wxsw_disassembly, idDisassemblyTextCtrl); wxrt_disassembly->SetCaretLineVisible(true); wxFont font(wxFontInfo().Family(wxFONTFAMILY_TELETYPE)); wxrt_disassembly->StyleSetFont((int)disas8051::Styles::DEFAULT, font); wxrt_disassembly->StyleSetFont((int)disas8051::Styles::BUF_ADDRESS, font); wxrt_disassembly->StyleSetForeground((int)disas8051::Styles::BUF_ADDRESS, wxColour(0, 255, 0)); wxrt_disassembly->StyleSetFont((int)disas8051::Styles::BYTES, font); wxrt_disassembly->StyleSetForeground((int)disas8051::Styles::BYTES, wxColour(0, 100, 0)); wxrt_disassembly->StyleSetFont((int)disas8051::Styles::RET_INSTRUCTION, font); wxrt_disassembly->StyleSetForeground((int)disas8051::Styles::RET_INSTRUCTION, wxColour(200, 0, 0)); wxrt_disassembly->StyleSetFont((int)disas8051::Styles::COMMENT, font); wxrt_disassembly->StyleSetForeground((int)disas8051::Styles::COMMENT, wxColour(200, 0, 0)); annotation_canvas->lineHeight = font.GetPixelSize().GetHeight(); std::cout << "LineHeight: " << annotation_canvas->lineHeight << std::endl; #ifdef _WIN32 // also 64-bit annotation_canvas->lineHeight += 3; // no time to check why this is needed #endif c_logger->LogInformation("Generating text viewer content..."); disassembly->printToWx(wxrt_disassembly); c_logger->LogInformation("Generated text viewer content."); wxsw_disassembly->SplitVertically(annotation_canvas, wxrt_disassembly, 100); wxsw_disassembly->SetMinimumPaneSize(10); // prevent unsplitting wxsz_left->Add(wxsw_disassembly, 1, wxALL | wxEXPAND, 2); wxStaticBoxSizer *wxsbz_current_line = new wxStaticBoxSizer(wxVERTICAL, panel_left, wxT("Current Line")); wxBoxSizer *wxsz_comment = new wxBoxSizer(wxHORIZONTAL); wxStaticText *lbl_comment = new wxStaticText(panel_left, wxID_ANY, wxT("Comment: ")); wxsz_comment->Add(lbl_comment, 0, wxALL, 2); wxtc_comment = new wxTextCtrl(panel_left, idTextCtrlComment, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_PROCESS_ENTER); wxtc_comment->SetToolTip(wxT("press enter to create or edit a comment at the current instruction")); wxsz_comment->Add(wxtc_comment, 1, wxALL, 2); wxsbz_current_line->Add(wxsz_comment, 0, wxALL | wxEXPAND, 2); wxBoxSizer *wxsz_function = new wxBoxSizer(wxHORIZONTAL); wxStaticText *lbl_function = new wxStaticText(panel_left, wxID_ANY, wxT("Function: ")); wxsz_function->Add(lbl_function, 0, wxALL, 2); wxtc_function = new wxTextCtrl(panel_left, idTextCtrlFunction, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_PROCESS_ENTER); wxtc_function->SetToolTip(wxT("press enter to create a function or rename a function at the current address")); wxsz_function->Add(wxtc_function, 1, wxALL, 2); wxc_function_shown = new wxCheckBox(panel_left, idCheckBoxFunctionShown, wxT("show")); wxc_function_shown->SetToolTip(wxT("whether the function is shown in the function call graph")); wxsz_function->Add(wxc_function_shown, 0, wxALL, 2); wxButton *wxb_delete_function = new wxButton(panel_left, idButtonDeleteFunction, wxT("delete")); wxsz_function->Add(wxb_delete_function, 0, wxALL, 2); wxsbz_current_line->Add(wxsz_function, 0, wxALL | wxEXPAND, 2); wxtc_function_blocks = new wxTextCtrl(panel_left, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_READONLY); wxsbz_current_line->Add(wxtc_function_blocks, 0, wxALL | wxEXPAND, 2); wxBoxSizer *wxsz_search = new wxBoxSizer(wxHORIZONTAL); wxStaticText *lbl_search = new wxStaticText(panel_left, wxID_ANY, wxT("Search: ")); wxsz_search->Add(lbl_search, 0, wxALL, 2); wxtc_search = new wxTextCtrl(panel_left, idTextCtrlSearch); wxsz_search->Add(wxtc_search, 1, wxALL, 2); wxc_search_hex = new wxCheckBox(panel_left, wxID_ANY, wxT("hex")); wxsz_search->Add(wxc_search_hex, 0, wxALL, 2); wxButton *wxb_find_before = new wxButton(panel_left, idButtonFindBefore, wxT("Previous")); wxsz_search->Add(wxb_find_before, 0, wxALL, 2); wxButton *wxb_find_next = new wxButton(panel_left, idButtonFindNext, wxT("Next")); wxsz_search->Add(wxb_find_next, 0, wxALL, 2); wxsbz_current_line->Add(wxsz_search, 0, wxALL | wxEXPAND, 2); wxtc_referalls = new wxTextCtrl(panel_left, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_READONLY); wxsbz_current_line->Add(wxtc_referalls, 0, wxALL | wxEXPAND, 2); wxsz_left->Add(wxsbz_current_line, 0, wxALL | wxEXPAND, 2); panel_left->SetSizerAndFit(wxsz_left); //wxPanel *panel_right = new wxPanel(wxsw_main); function_graph = new FunctionGraph(this, wxsw_main, wxID_ANY); function_graph->RefreshCache(); wxsw_main->SplitVertically(panel_left, function_graph, 500); wxsw_main->SetMinimumPaneSize(10); // prevent unsplitting wxsz_panel_disassembly->Add(wxsw_main, 1, wxALL | wxEXPAND, 2); panel_disassembly->SetSizerAndFit(wxsz_panel_disassembly); wxPanel *panel_log = new wxPanel(notebook); notebook->AddPage( panel_log, wxT("Log"), false); wxBoxSizer *wxsz_panel_log = new wxBoxSizer(wxVERTICAL); wxTextCtrl* wxtc_log = new wxTextCtrl(panel_log, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(500, 200), wxTE_MULTILINE | wxTE_READONLY | wxTE_RICH); c_logger->AddLogDisplay(wxtc_log, &c_gui_palette); wxsz_panel_log->Add(wxtc_log, 1, wxEXPAND | wxALL, 2); panel_log->SetSizerAndFit(wxsz_panel_log); notebook->SetSelection(0); // Activate the "Capture" tab topSizer->Insert(0, notebook, wxSizerFlags(5).Expand().Border()); topSizer->Layout(); SetSizer(topSizer); topSizer->Fit(this); topSizer->SetSizeHints(this); // create a status bar with some information about the used wxWidgets version CreateStatusBar(2); time_t now = time(NULL); tm *info = localtime(&now); if(info->tm_hour < 11) SetStatusText(_("Good Morning"),0); else if(info->tm_hour < 17) SetStatusText(_("Good Afternoon"),0); else SetStatusText(_("Good Evening"),0); SetStatusText(wxT("Copyright Matthias Rosenthal"), 1); timer_gui_update1.Start(TIMER_GUI_UPDATE_INTERVAL_MS); SetSize(wxSize(1200, 900)); wxrt_disassembly->SetEditable(false); } Dis8051Frame::~Dis8051Frame() { c_logger.reset(); gui_palette_end(c_gui_palette); } void Dis8051Frame::OnClose(wxCloseEvent &event) { std::cout << "stopping" << std::endl; timer_gui_update1.Stop(); std::cout << "stopped." << std::endl; Destroy(); } void Dis8051Frame::OnQuit(wxCommandEvent &event) { std::cout << "stopping" << std::endl; timer_gui_update1.Stop(); std::cout << "stopped." << std::endl; Destroy(); } void Dis8051Frame::OnAbout(wxCommandEvent &event) { wxString msg = wxT("Interactive 8051 disassembler\n" "Currently targeted for ENE KB9012 (Keyboard Controller)\nCopyright Matthias Rosenthal\n") + fn_wxbuildinfo(wxbuildinfof_long_f); wxMessageBox(msg, _("Welcome to...")); } void Dis8051Frame::OnTimerUpdateUI(wxTimerEvent& event) { c_logger->updateLogDisplays(); } void Dis8051Frame::OnSaveMetaFile(wxCommandEvent &event) { disassembly->saveMetaFile(metaFile); messageGUI("Saved to " + metaFile); } void Dis8051Frame::OnDisassemblyTextUpdated(wxStyledTextEvent &event) { if(event.GetUpdated() & wxSTC_UPDATE_V_SCROLL) { scroll_overview->Refresh(); annotation_canvas->Refresh(); } if(event.GetUpdated() & wxSTC_UPDATE_SELECTION) { OnDissassemblyCaretMove(); } } void Dis8051Frame::OnDissassemblyCaretMove() { int currentLine = wxrt_disassembly->GetCurrentLine(); auto itAddress = disassembly->addressByLine.find(currentLine); if(itAddress != disassembly->addressByLine.end()) { auto itInstruction = disassembly->instructions.find(itAddress->second); if(itInstruction != disassembly->instructions.end()) { wxtc_comment->SetValue(wxString::FromUTF8(itInstruction->second.comment.c_str())); SetStatusText(wxString::FromUTF8(("Address: " + utils::Int_To_String_Hex(itAddress->second) + ", Bytes: " + fn_FormatToHex(disassembly->buf.substr(itAddress->second, itInstruction->second.length), true)).c_str()), 0); } else { wxtc_comment->SetValue(wxEmptyString); SetStatusText(wxString::Format(wxT("Address: %5x"), (int)itAddress->second), 0); } auto itTarget = disassembly->jumpTargets.find(itAddress->second); if(itTarget != disassembly->jumpTargets.end()) { if(!itTarget->second.empty()) { std::string references = "Referenced by " + getAddressDescription(itTarget->second[0]); for(std::size_t i1 = 1; i1 < itTarget->second.size(); i1++) { references += ", " + getAddressDescription(itTarget->second[i1]); } wxtc_referalls->SetValue(wxString::FromUTF8(references.c_str())); } else { wxtc_referalls->SetValue(wxEmptyString); } } else { wxtc_referalls->SetValue(wxEmptyString); } auto itFunction = disassembly->findFunction(itAddress->second); if(itFunction != disassembly->functions.end()) { wxtc_function->SetValue(wxString::FromUTF8(itFunction->second.name.c_str())); wxtc_function_blocks->SetValue(wxString::FromUTF8(itFunction->second.getBlockSummary().c_str())); wxc_function_shown->SetValue(itFunction->second.isShownInGraph); } else { wxtc_function->SetValue(wxEmptyString); wxtc_function_blocks->SetValue(wxEmptyString); wxc_function_shown->SetValue(false); } return; } wxtc_comment->SetValue(wxEmptyString); wxtc_referalls->SetValue(wxEmptyString); wxtc_function->SetValue(wxEmptyString); } void Dis8051Frame::OnOverviewLineClicked(int line) { wxrt_disassembly->SetFocus(); wxrt_disassembly->GotoLine(line); } void Dis8051Frame::OnFunctionClicked(uint64_t address, disas8051::Function *function) { int line = disassembly->findLineByAddress(address); if(line < 0) { c_logger->LogError("Line should have been existed"); return; } wxrt_disassembly->SetFocus(); wxrt_disassembly->GotoLine(line); } void Dis8051Frame::GetDisassemblyLinesOnScreen(int *lineBegin, int *lineEnd) { *lineBegin = wxrt_disassembly->GetFirstVisibleLine(); *lineEnd = *lineBegin + wxrt_disassembly->LinesOnScreen(); } void Dis8051Frame::doSearch(bool previous) { if(wxc_search_hex->GetValue()) { std::string hexstring = fn_wxUTF8String_ToUTF8String(wxtc_search->GetValue()); std::size_t ihexstring = 0; disas8051::ustring searchbytes; while(true) { while((ihexstring < hexstring.size() && (hexstring[ihexstring] == ' '))) { ihexstring++; } if(ihexstring == hexstring.size()) { break; } if(ihexstring + 2 > hexstring.size()) { messageGUI("invalid hexstring: it does not end with a block of two hex digits"); return; } if((!utils::is_hexchar(hexstring[ihexstring])) || (!utils::is_hexchar(hexstring[ihexstring+1]))) { messageGUI("invalid hex digit"); return; } searchbytes.append(1, utils::Hex_To_uint8(hexstring[ihexstring], hexstring[ihexstring+1])); ihexstring += 2; } if(searchbytes.empty()) { messageGUI("empty search string"); return; } int currentLine = wxrt_disassembly->GetCurrentLine(); auto itAddress = disassembly->addressByLine.find(currentLine); if(itAddress == disassembly->addressByLine.end()) { messageGUI("no address corresponding to that line"); return; } std::size_t pos; if(previous) { if(itAddress->second <= 0) { messageGUI("Not found"); return; } pos = disassembly->buf.rfind(searchbytes, itAddress->second - 1); std::cout << "searching backwards from " << utils::Int_To_String_Hex(itAddress->second) << ": " << fn_FormatToHex(searchbytes, true) << std::endl; } else { pos = disassembly->buf.find(searchbytes, itAddress->second + 1); std::cout << "searching forwards from " << utils::Int_To_String_Hex(itAddress->second) << ": " << fn_FormatToHex(searchbytes, true) << std::endl; } if(pos == std::string::npos) { messageGUI("Not found"); return; } int line = disassembly->findLineByAddress(pos); if(line >= 0) { wxrt_disassembly->GotoLine(line); wxrt_disassembly->SetFocus(); } else { messageGUI("Could not find line corresponding to position found"); } } else { wxrt_disassembly->SearchAnchor(); std::cout << "searching for \"" + fn_wxUTF8String_ToUTF8String(wxtc_search->GetValue()) << '"' << std::endl; int pos; if(previous) { pos = wxrt_disassembly->SearchPrev(wxSTC_FIND_MATCHCASE, wxtc_search->GetValue()); } else { pos = wxrt_disassembly->SearchNext(wxSTC_FIND_MATCHCASE, wxtc_search->GetValue()); } if(pos >= 0) { std::cout << (previous ? 1 : 0) << " goto " << (pos + (previous ? 0 : 1)) << std::endl; wxrt_disassembly->GotoPos(pos + (previous ? 0 : 1)); // without '+1' on next search, the next match would be the same wxrt_disassembly->SetFocus(); } else { messageGUI("Not found"); } } } void Dis8051Frame::OnFindBefore(wxCommandEvent &event) { doSearch(true); } void Dis8051Frame::OnFindNext(wxCommandEvent &event) { doSearch(false); } void Dis8051Frame::OnGoto(wxCommandEvent &event) { int address = queryAddressFromUser(wxT("Goto")); if(address >= 0) { int line = disassembly->findLineByAddress(address); if(line >= 0) { wxrt_disassembly->GotoLine(line); wxrt_disassembly->SetFocus(); } else { messageGUI("Could not find corresponding line"); } } } void Dis8051Frame::OnCommentEnterPressed(wxCommandEvent &event) { wxSTCEditableLocker disasLocker(wxrt_disassembly); int currentLine = wxrt_disassembly->GetCurrentLine(); auto itAddress = disassembly->addressByLine.find(currentLine); if(itAddress != disassembly->addressByLine.end()) { auto itInstruction = disassembly->instructions.find(itAddress->second); if(itInstruction != disassembly->instructions.end()) { disassembly->updateInstructionComment(itAddress->second, fn_wxUTF8String_ToUTF8String(wxtc_comment->GetValue())); messageGUI("Updated comment"); } else { messageGUI("No instruction corresponding to that address"); } } else { messageGUI("No address corresponding to that line"); } } void Dis8051Frame::OnFunctionEnterPressed(wxCommandEvent &event) { wxSTCEditableLocker disasLocker(wxrt_disassembly); int currentLine = wxrt_disassembly->GetCurrentLine(); auto itAddress = disassembly->addressByLine.find(currentLine); std::string name = fn_wxUTF8String_ToUTF8String(wxtc_function->GetValue()); if(itAddress != disassembly->addressByLine.end()) { auto itFunction = disassembly->functions.find(itAddress->second); if(itFunction != disassembly->functions.end()) { if(name.empty()) { messageGUI("Please press the delete button to confirm that you really want to delete that function"); } else { disassembly->updateFunctionName(itAddress->second, name); function_graph->RefreshCache(); function_graph->Refresh(); messageGUI("Renamed function to " + name); } } else { if(name.empty()) { messageGUI("No empty name allowed"); } else { disas8051::Function function; function.posX = 10; function.posY = 10; function.isInterrupt = false; function.name = name; if(disassembly->instructions.find(itAddress->second) == disassembly->instructions.end()) { int address = queryAddressFromUser(wxT("Enter address of the new function"), (int)itAddress->second); if(address >= 0) { disassembly->addFunction(address, function); scroll_overview->Refresh(); // we disassembled some code function_graph->RefreshCache(); function_graph->Refresh(); wxc_function_shown->SetValue(true); messageGUI("Added function " + name); } } else { disassembly->addFunction(itAddress->second, function); function_graph->RefreshCache(); function_graph->Refresh(); messageGUI("Added function " + name); } } } } else { messageGUI("No address"); } } void Dis8051Frame::OnToggleFunctionShown(wxCommandEvent &event) { int currentLine = wxrt_disassembly->GetCurrentLine(); auto itAddress = disassembly->addressByLine.find(currentLine); if(itAddress != disassembly->addressByLine.end()) { auto itFunction = disassembly->findFunction(itAddress->second); if(itFunction != disassembly->functions.end()) { itFunction->second.isShownInGraph = wxc_function_shown->GetValue(); function_graph->Refresh(); } else { messageGUI("No function on this address"); } } else { messageGUI("No function on this line"); } } void Dis8051Frame::OnFunctionDelete(wxCommandEvent &event) { wxSTCEditableLocker disasLocker(wxrt_disassembly); int currentLine = wxrt_disassembly->GetCurrentLine(); auto itAddress = disassembly->addressByLine.find(currentLine); if(itAddress != disassembly->addressByLine.end()) { auto itFunction = disassembly->findFunction(itAddress->second); if(itFunction != disassembly->functions.end()) { messageGUI("Deleted function " + itFunction->second.name); disassembly->deleteFunction(itFunction->first); wxtc_function->SetValue(wxEmptyString); wxtc_function_blocks->SetValue(wxEmptyString); function_graph->RefreshCache(); function_graph->Refresh(); } else { messageGUI("No function on this address"); } } else { messageGUI("No function on this line"); } } void Dis8051Frame::OnToggleCallAnnotation(wxCommandEvent &event) { annotation_canvas->annotateCalls = !annotation_canvas->annotateCalls; annotation_canvas->Refresh(); } void Dis8051Frame::OnReadAddressFromCode(wxCommandEvent &event) { int address = queryAddressFromUser("Copy 16-Bit address from code to clipboard"); if(address >= 0) { // Write some text to the clipboard if (wxTheClipboard->Open()) { std::string addressStr = fn_FormatToHex(disassembly->buf.substr(address, 1), true) + fn_FormatToHex(disassembly->buf.substr(address+1, 1), true); // This data objects are held by the clipboard, // so do not delete them in the app. wxTheClipboard->SetData(new wxTextDataObject(wxString::FromUTF8(addressStr.c_str()))); wxTheClipboard->Close(); messageGUI("Copied " + addressStr + " to clipboard."); } else { messageGUI("Could not open clipboard."); } } } void Dis8051Frame::messageGUI(std::string msg) { SetStatusText(wxString::FromUTF8(msg.c_str()), 0); c_logger->LogInformation(msg); } std::string Dis8051Frame::getAddressDescription(uint64_t address) { std::string str = disassembly->formatWithFunction(address); if(disassembly->instructions[address].isCall()) { str += " (call)"; } return str; } std::basic_string<uint8_t> Uint16t_To_UString(uint16_t var) { return std::basic_string<uint8_t>(1, *((uint8_t*)&var)) + std::basic_string<uint8_t>(1, *((uint8_t*)&var + 1)); } int Dis8051Frame::queryAddressFromUser(wxString title, int defaultAddress) { wxTextEntryDialog dlg(this, wxT("Hex address"), title); if(defaultAddress >= 0) { dlg.SetValue(wxString::Format(wxT("%x"), defaultAddress)); } if(dlg.ShowModal() == wxID_OK) { utils::string_to_int_limited_converter convertobj; uint64_t address = convertobj.ConvertToLLI_Hex_Limited( fn_wxUTF8String_ToUTF8String(dlg.GetValue()), 0, disassembly->buf.length()); if(convertobj.MistakeHappened() || convertobj.LimitMistakeHappened()) { messageGUI("Invalid address"); return -1; } else { return address; } } else { return -1; } }
28,009
C++
.cpp
622
38.451768
175
0.679345
msrst/interactive-8051-disassembler
39
5
1
GPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,861
wxApp.cpp
msrst_interactive-8051-disassembler/wxApp.cpp
/************************************************************************ * Copyright (C) 2020-2021 Matthias Rosenthal * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/> ***********************************************************************/ #include <unistd.h> #include "wx/cmdline.h" #include "wx/filedlg.h" #include "wx/filename.h" #include "wxApp.h" #include "wxMain.h" #include "utils/utils_wx.h" #ifndef _WIN32 #include "res/kassette.xpm" #endif IMPLEMENT_APP(Dis8051App); const std::string FILE_UNDEFINED_STR = "undefined"; Dis8051App::Dis8051App() { firmwareFile = FILE_UNDEFINED_STR; metaFile = FILE_UNDEFINED_STR; } void Dis8051App::OnInitCmdLine(wxCmdLineParser &parser) { // Wichtig: Unicode-Zeichen sorgen daf�r, dass ./programm --help nichts ausgibt! wxApp::OnInitCmdLine(parser); parser.AddSwitch(wxT("v"), wxT("version"), wxT("Gibt die Version aus")); parser.AddLongOption(wxT("mfile"), wxT("Metadata filename, e. g. meta.txt, default: <firmware_file>.txt"), wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL); parser.AddParam(wxT("Firmware filename, e. g. in.bin"), wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL); } bool Dis8051App::OnCmdLineParsed(wxCmdLineParser &parser) { if(!(wxApp::OnCmdLineParsed(parser))) { std::cout << "Error parsing the command line." << std::endl; return false; } // Check if the user asked for the version if(parser.Found(wxT("v"))) { #ifndef __WXMSW__ wxLog::SetActiveTarget(new wxLogStderr); #endif // __WXMSW__ wxLogMessage(wxT("8051 disassembler") wxT("\nBuild-Datum: ") + wxString::FromAscii(__DATE__) + wxT("\nCopyright Matthias Rosenthal")); return false; } wxString wxs_zws1; if(parser.Found(wxT("mfile"), &wxs_zws1)) { metaFile = fn_wxUTF8String_ToUTF8String(wxs_zws1); } // Check for a filename if(parser.GetParamCount() > 0) { wxString wxFirmwareFile = parser.GetParam(0); // Under Windows when invoking via a document in Explorer, we are passed the short form. // So normalize and make the long form. wxFileName fName(wxFirmwareFile); fName.Normalize(wxPATH_NORM_LONG|wxPATH_NORM_DOTS|wxPATH_NORM_TILDE|wxPATH_NORM_ABSOLUTE); firmwareFile = fn_wxUTF8String_ToUTF8String(fName.GetFullPath()); } if(firmwareFile == FILE_UNDEFINED_STR) { while(true) { wxFileDialog openFileDialog(nullptr, _("Open firmware file (meta file = <firmware_filename>.txt)"), "", "", "Binary files (*.*)|*.*", wxFD_OPEN|wxFD_FILE_MUST_EXIST); if (openFileDialog.ShowModal() != wxID_OK) { return false; } firmwareFile = fn_wxUTF8String_ToUTF8String(openFileDialog.GetPath()); if(utils::str_ends_with(firmwareFile, ".txt")) { // This is actually a tradeoff between annoying users who store their binary // firmware in txt format vs. the great majority of users who don't do that. // But if necessary, they can use the command line options. wxString message = wxString::FromUTF8(("This message wants to warn you in case you accidentally" " selected the metadata file instead of the firmware file, because the firmware file you " "selected in the previous file dialog ends with '.txt'.\n\n" "Are you sure to use the file \"" + firmwareFile + "\" as the firmware (other word: binary) file which is gonna be disassembled?\n\n").c_str()); wxMessageDialog dlg(nullptr, message, _("Firmware file"), wxYES | wxNO | wxCENTRE); if(dlg.ShowModal() == wxID_YES) { break; } } else { break; } } } if(metaFile == FILE_UNDEFINED_STR) { metaFile = firmwareFile + ".txt"; } return true; } bool Dis8051App::OnInit() { if(!wxApp::OnInit()) { return false; } Dis8051Frame* frame = new Dis8051Frame(0L, wxT("interactive 8051 disassembler"), firmwareFile, metaFile, this); #ifdef _WIN32 frame->SetIcon(wxICON(aaaa)); // described in resource file #else frame->SetIcon(wxIcon(kassette_xpm)); #endif frame->Show(); return true; } int Dis8051App::OnExit() { std::cout << "bye." << std::endl; return 0; }
5,193
C++
.cpp
123
34.422764
143
0.615109
msrst/interactive-8051-disassembler
39
5
1
GPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,862
function_graph.cpp
msrst_interactive-8051-disassembler/function_graph.cpp
/************************************************************************ * Copyright (C) 2020-2021 Matthias Rosenthal * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/> ***********************************************************************/ #include "function_graph.hpp" #include "wxMain.h" #include <iostream> BEGIN_EVENT_TABLE(FunctionGraph, wxScrolledCanvas) EVT_LEFT_DOWN(FunctionGraph::OnLeftDown) EVT_MOTION(FunctionGraph::OnMouseMove) EVT_LEFT_UP(FunctionGraph::OnLeftUp) EVT_KEY_DOWN(FunctionGraph::OnKeyDown) EVT_LEFT_DCLICK(FunctionGraph::OnLeftDClick) EVT_MOUSEWHEEL(FunctionGraph::OnMouseWheel) END_EVENT_TABLE() FunctionGraph::FunctionGraph(Dis8051Frame* mainFrame, wxWindow *parent, wxWindowID id) : wxScrolledCanvas(parent, id, wxDefaultPosition, wxSize(150, 300)), font(wxFontInfo(9)) { this->mainFrame = mainFrame; w = 1600; h = 5000; /* init scrolled area size, scrolling speed, etc. */ SetScrollbars(10,10, w/10, h/10, 0, 0); } void FunctionGraph::OnDraw(wxDC& dc) { wxPen indirectRemapCallPen(wxColor(120, 120, 255)); int viewStartX, viewStartY, viewSizeX, viewSizeY; GetViewStart(&viewStartX, &viewStartY); GetClientSize(&viewSizeX, &viewSizeY); //std::cout << viewStartX << " " << viewStartY << " " << viewSizeX << " " << viewSizeY << std::endl; dc.SetFont(font); dc.SetPen(*wxBLACK_PEN); for(std::size_t iFunction = 0; iFunction < cachedFunctions.size(); iFunction++) { const CachedFunction &cFunction = cachedFunctions[iFunction]; if(!cFunction.function->isShownInGraph) { continue; } //std::cout << iFunction << " " << cFunction.address << " " << cFunction.function->posX << " " << cFunction.function->posY << std::endl; int offsetX = 0; int offsetY = 0; if(isDragging && isDraggingFunction && (iFunction == draggedFunctionIndex)) { offsetX = dragCurrentX - dragStartX; offsetY = dragCurrentY - dragStartY; //std::cout << "offset " << offsetX << " " << offsetY << std::endl; } if(cFunction.function->isInterrupt) { dc.SetBrush(*wxGREY_BRUSH); } else { dc.SetBrush(*wxWHITE_BRUSH); } dc.DrawRectangle(cFunction.function->posX + offsetX, cFunction.function->posY + offsetY, cFunction.rectWidth, cFunction.rectHeight); dc.DrawText(wxString::FromUTF8(cFunction.function->name.c_str()), cFunction.function->posX + offsetX + MARGIN, cFunction.function->posY + offsetY + MARGIN); } for(std::size_t iFunction = 0; iFunction < cachedFunctions.size(); iFunction++) { const CachedFunction &cFunction = cachedFunctions[iFunction]; if(!cFunction.function->isShownInGraph) { continue; } for(const auto &pair : cFunction.targetIndexes) { if(pair.first == iFunction) { continue; } if(!cachedFunctions[pair.first].function->isShownInGraph) { continue; } dc.SetPen(pair.second ? (*wxBLACK_PEN) : (*wxGREY_PEN)); if(cachedFunctions[pair.first].function->name.find("PUTCHAR") != std::string::npos) { dc.SetPen(*wxRED_PEN); } DrawConnectorLine(&dc, cFunction.function->posX + cFunction.rectWidth, cFunction.function->posY + cFunction.rectHeight / 2, cachedFunctions[pair.first].function->posX, cachedFunctions[pair.first].function->posY + cachedFunctions[pair.first].rectHeight / 2); } for(int iRemapCall : cFunction.remapCallIndexes) { const CachedRemapCall &cRemapCall = cachedRemapCalls[iRemapCall]; if(cRemapCall.targetIndex >= 0) { if(!cachedFunctions[cRemapCall.targetIndex].function->isShownInGraph) { continue; } dc.SetPen(cRemapCall.isDirectCall ? (*wxBLUE_PEN) : indirectRemapCallPen); DrawConnectorLine(&dc, cFunction.function->posX + cFunction.rectWidth, cFunction.function->posY + cFunction.rectHeight / 2, cachedFunctions[cRemapCall.targetIndex].function->posX, cachedFunctions[cRemapCall.targetIndex].function->posY + cachedFunctions[cRemapCall.targetIndex].rectHeight / 2); } } } /*dc.SetBrush(wxBrush(wxColor(100, 100, 255))); for(int iRemapCall = 0; iRemapCall < cachedRemapCalls.size(); iRemapCall++) { const CachedRemapCall &cRemapCall = cachedRemapCalls[iRemapCall]; int offsetX = 0; int offsetY = 0; if(isDragging && (!isDraggingFunction) && (iRemapCall == draggedFunctionIndex)) { offsetX = dragCurrentX - dragStartX; offsetY = dragCurrentY - dragStartY; //std::cout << "offset " << offsetX << " " << offsetY << std::endl; } dc.DrawRectangle(cRemapCall.remapCall->posX + offsetX, cRemapCall.remapCall->posY + offsetY, cRemapCall.rectWidth, cRemapCall.rectHeight); dc.DrawText(wxString::Format(wxT("%x"), (int)cRemapCall.remapCall->targetAddress), cRemapCall.remapCall->posX + offsetX + MARGIN, cRemapCall.remapCall->posY + offsetY + MARGIN); }*/ } void FunctionGraph::DrawConnectorLine(wxDC *dc, int x1, int y1, int x2, int y2) { const int BACKWARDS_MARGIN_X = 2; const int BACKWARDS_MARGIN_Y = 12; int xDiff = x2 - x1; if(xDiff >= 0) { wxPoint points[4]; points[0] = wxPoint(x1, y1); points[1] = wxPoint(x1 + xDiff / 2, y1); points[2] = wxPoint(x1 + xDiff / 2, y2); points[3] = wxPoint(x2, y2); dc->DrawLines(4, points); } else { wxPoint points[8]; points[0] = wxPoint(x1, y1); points[1] = wxPoint(x1 + BACKWARDS_MARGIN_X, y1); points[2] = wxPoint(x1 + BACKWARDS_MARGIN_X, y1 + BACKWARDS_MARGIN_Y); points[3] = wxPoint(x1 + xDiff / 2, y1 + BACKWARDS_MARGIN_Y); points[4] = wxPoint(x1 + xDiff / 2, y2 + BACKWARDS_MARGIN_Y); points[5] = wxPoint(x2 - BACKWARDS_MARGIN_X, y2 + BACKWARDS_MARGIN_Y); points[6] = wxPoint(x2 - BACKWARDS_MARGIN_X, y2); points[7] = wxPoint(x2, y2); dc->DrawLines(8, points); } } void FunctionGraph::OnLeftDown(wxMouseEvent &event) { wxPoint mousePos = CalcUnscrolledPosition(ScreenToClient(wxGetMousePosition())); event.Skip(); // let the function graph window get the focus int iFunction = getFunctionIndex(mousePos); if(iFunction >= 0) { draggedFunctionIndex = iFunction; dragStartX = mousePos.x; dragStartY = mousePos.y; isDragging = true; } } int FunctionGraph::getFunctionIndex(wxPoint mousePos) { for(std::size_t iFunction = 0; iFunction < cachedFunctions.size(); iFunction++) { const CachedFunction &cFunction = cachedFunctions[iFunction]; if(!cFunction.function->isShownInGraph) { continue; } if((mousePos.x >= cFunction.function->posX - MARGIN) && (mousePos.x < cFunction.function->posX + cFunction.rectWidth + MARGIN) && (mousePos.y >= cFunction.function->posY - MARGIN) && (mousePos.y < cFunction.function->posY + cFunction.rectHeight + MARGIN)) { //std::cout << "hit function " << iFunction << cFunction.function->name << std::endl; return iFunction; } } return -1; } void FunctionGraph::OnMouseMove(wxMouseEvent &event) { wxPoint mousePos = CalcUnscrolledPosition(ScreenToClient(wxGetMousePosition())); if(isDragging) { //int oldDragX = dragCurrentX; //int oldDragY = dragCurrentY; dragCurrentX = mousePos.x; dragCurrentY = mousePos.y; Refresh(); // TODO use RefreshRect here from oldDragXY to dragCurrentXY, it's flickering really too much under windows } } void FunctionGraph::OnLeftUp(wxMouseEvent &event) { wxPoint mousePos = CalcUnscrolledPosition(ScreenToClient(wxGetMousePosition())); if(isDragging) { CachedFunction &cFunction = cachedFunctions[draggedFunctionIndex]; cFunction.function->posX += mousePos.x - dragStartX; cFunction.function->posY += mousePos.y - dragStartY; isDragging = false; Refresh(); } } void FunctionGraph::OnKeyDown(wxKeyEvent &event) { wxChar key = event.GetKeyCode(); if(key == WXK_ESCAPE) { if(isDragging) { isDragging = false; Refresh(); } } } void FunctionGraph::OnLeftDClick(wxMouseEvent &event) { wxPoint mousePos = CalcUnscrolledPosition(ScreenToClient(wxGetMousePosition())); event.Skip(); // let the function graph window get the focus int iFunction = getFunctionIndex(mousePos); if(iFunction >= 0) { mainFrame->OnFunctionClicked(cachedFunctions[iFunction].address, cachedFunctions[iFunction].function); } } // -1 if not found int searchFunction(disas8051::Disassembly *disassembly, const std::unordered_map<uint64_t, std::size_t> &addressToFunction, int address, bool &directCall) { auto itFunction = addressToFunction.find(address); if(itFunction == addressToFunction.end()) { auto itDisFunction = disassembly->findFunction(address); if(itDisFunction != disassembly->functions.end()) { // call / jump to a part of the function itFunction = addressToFunction.find(itDisFunction->first); directCall = false; return itFunction->second; } } else { directCall = true; return itFunction->second; } return -1; } void FunctionGraph::RefreshCache() { wxMemoryDC dc; dc.SetFont(font); std::unordered_map<uint64_t, std::size_t> addressToFunction; cachedFunctions.resize(mainFrame->getDisassembly()->functions.size()); std::size_t iFunction = 0; for(auto &pair : mainFrame->getDisassembly()->functions) { CachedFunction cachedFunction; cachedFunction.address = pair.first; cachedFunction.function = &(pair.second); dc.GetTextExtent(wxString::FromUTF8(pair.second.name.c_str()), &(cachedFunction.rectWidth), &(cachedFunction.rectHeight)); cachedFunction.rectWidth += MARGIN * 2; // #ifdef __unix__ // // I really don't know why this is necessary, but it seemed to be only // // to be the double height since I changed wxWidgets from the ubuntu built-in // // to wx3.1.3 // cachedFunction.rectHeight = cachedFunction.rectHeight / 2 + MARGIN * 2; // #else cachedFunction.rectHeight += MARGIN * 2; // #endif cachedFunctions[iFunction] = cachedFunction; addressToFunction[pair.first] = iFunction; iFunction++; } std::unordered_map<uint64_t, int> addressToRemapCall; cachedRemapCalls.resize(mainFrame->getDisassembly()->remapCalls.size()); int iRemapCall = 0; for(auto &pair : mainFrame->getDisassembly()->remapCalls) { CachedRemapCall cachedRemapCall; cachedRemapCall.address = pair.first; cachedRemapCall.remapCall = &(pair.second); dc.GetTextExtent(wxString::Format(wxT("%x"), (int)pair.second.targetAddress), &(cachedRemapCall.rectWidth), &(cachedRemapCall.rectHeight)); cachedRemapCall.rectWidth += MARGIN * 2; cachedRemapCall.rectHeight += MARGIN * 2; cachedRemapCall.targetIndex = searchFunction(mainFrame->getDisassembly(), addressToFunction, pair.second.targetAddress, cachedRemapCall.isDirectCall); cachedRemapCalls[iRemapCall] = cachedRemapCall; addressToRemapCall[pair.first] = iRemapCall; iRemapCall++; } for(iFunction = 0; iFunction < cachedFunctions.size(); iFunction++) { CachedFunction &cFunction = cachedFunctions[iFunction]; std::vector<uint64_t> sourceAddresses = mainFrame->getDisassembly()->GetFunctionTargetAddresses(cFunction.address); for(uint64_t sourceAddress : sourceAddresses) { bool directCall; int index = searchFunction(mainFrame->getDisassembly(), addressToFunction, sourceAddress, directCall); if(index >= 0) { if(directCall) { cFunction.targetIndexes[index] = true; } else { auto itTargetIndex = cFunction.targetIndexes.find(cachedFunctions[index].address); if(itTargetIndex == cFunction.targetIndexes.end()) { // do not override if there is also a jump / call to the first address cFunction.targetIndexes[index] = false; } } } auto itRemapCall = addressToRemapCall.find(sourceAddress); if(itRemapCall != addressToRemapCall.end()) { cFunction.remapCallIndexes.push_back(itRemapCall->second); } } } } void FunctionGraph::OnMouseWheel(wxMouseEvent &event) { // wxScrollCanvas only implements vertical scrolling by default double rotation = event.GetWheelRotation() / event.GetWheelDelta(); if(event.ShiftDown()) { Scroll(GetViewStart() + wxSize(-rotation * 3, 0)); } else { Scroll(GetViewStart() + wxSize(0, -rotation * 3)); } }
13,385
C++
.cpp
313
36.744409
154
0.675759
msrst/interactive-8051-disassembler
39
5
1
GPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,863
scroll_overview.cpp
msrst_interactive-8051-disassembler/scroll_overview.cpp
/************************************************************************ * Copyright (C) 2020-2021 Matthias Rosenthal * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/> ***********************************************************************/ #include "scroll_overview.hpp" #include "wxMain.h" #include <iostream> BEGIN_EVENT_TABLE(ScrollOverview, wxScrolledWindow) EVT_LEFT_DOWN(ScrollOverview::OnLeftDown) END_EVENT_TABLE() const int YSCROLL_STEP_SIZE = 10; ScrollOverview::ScrollOverview(Dis8051Frame* mainFrame, wxWindow *parent, wxWindowID id) : wxScrolledWindow(parent, id, wxDefaultPosition, wxSize(150, 300)) { this->mainFrame = mainFrame; w = 400; h = mainFrame->getDisassembly()->buf.length(); /* init scrolled area size, scrolling speed, etc. */ SetScrollbars(1, YSCROLL_STEP_SIZE, w, h/YSCROLL_STEP_SIZE + 1, 0, 0); } void ScrollOverview::OnDraw(wxDC& dc) { const int LINE_WIDTH = 80; const int CODEVIEW_RECT_WIDTH = 30; wxPen invalidCodePen = wxPen(wxColor(180, 180, 0)); wxPen unparsedCodePen = wxPen(wxColor(200, 200, 200)); int viewStartX, viewStartY, viewSizeX, viewSizeY; GetViewStart(&viewStartX, &viewStartY); GetClientSize(&viewSizeX, &viewSizeY); viewStartY *= YSCROLL_STEP_SIZE; int lineBegin, lineEnd; mainFrame->GetDisassemblyLinesOnScreen(&lineBegin, &lineEnd); auto it = mainFrame->getDisassembly()->instructions.begin(); int address = viewStartY; while(it != mainFrame->getDisassembly()->instructions.end()) { if(int(it->first + it->second.length) >= address) { break; } it++; } int yEnd = std::min(viewStartY + viewSizeY, (int)mainFrame->getDisassembly()->buf.length()); //std::cout << viewStartX << " " << viewStartY << " " << viewSizeX << " " << viewSizeY << " " << yEnd << " on " << lineBegin << " - " << lineEnd << std::endl; if(it != mainFrame->getDisassembly()->instructions.end()) { for(; address < yEnd; address++) { if(int(it->first + it->second.length) < address) { it++; if(it == mainFrame->getDisassembly()->instructions.end()) { break; } } if(int(it->first) > address) { dc.SetPen(unparsedCodePen); if(mainFrame->getDisassembly()->seemsToBeInvalidCode(address)) { dc.SetPen(invalidCodePen); } } else { if(it->second.getName() == "RET") { dc.SetPen(*wxRED_PEN); } else if(it->second.getName() == "RETI") { dc.SetPen(*wxCYAN_PEN); } else { dc.SetPen(*wxWHITE_PEN); } } dc.DrawLine(0, address, LINE_WIDTH, address); } } for(; address < yEnd; address++) { if(mainFrame->getDisassembly()->seemsToBeInvalidCode(address)) { dc.SetPen(invalidCodePen); } else { dc.SetPen(unparsedCodePen); } dc.DrawLine(0, address, LINE_WIDTH, address); } dc.SetBrush(*wxBLACK_BRUSH); auto itLineBegin = mainFrame->getDisassembly()->addressByLine.find(lineBegin); if(itLineBegin != mainFrame->getDisassembly()->addressByLine.end()) { if(std::abs((int)itLineBegin->second - viewStartY) < 5000) { // this is because wxDC seems to clip at // 16-bit pixel integers, which results in the current position displayed at 0 but also at 65535 auto itLineEnd = mainFrame->getDisassembly()->addressByLine.find(lineEnd); if(itLineEnd == mainFrame->getDisassembly()->addressByLine.end()) { dc.DrawRectangle(LINE_WIDTH + 10, itLineBegin->second, CODEVIEW_RECT_WIDTH, mainFrame->getDisassembly()->buf.length() - itLineBegin->second); } else { dc.DrawRectangle(LINE_WIDTH + 10, itLineBegin->second, CODEVIEW_RECT_WIDTH, itLineEnd->second - itLineBegin->second); } } } } void ScrollOverview::OnLeftDown(wxMouseEvent &event) { wxPoint mousePos = CalcUnscrolledPosition(ScreenToClient(wxGetMousePosition())); int lineBegin = mainFrame->getDisassembly()->findLineByAddress(mousePos.y); if(lineBegin > 0) { //std::cout << "left down at " << mousePos.x << " " << mousePos.y << " -> " << lineBegin << std::endl; mainFrame->OnOverviewLineClicked(lineBegin); // do not get the focus, because the focus is given to the disassembly window to mark the current line } else { event.Skip(); // let the scroll overview window get the focus } }
5,236
C++
.cpp
119
36.579832
162
0.616575
msrst/interactive-8051-disassembler
39
5
1
GPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,864
annotation_canvas.cpp
msrst_interactive-8051-disassembler/annotation_canvas.cpp
/************************************************************************ * Copyright (C) 2020-2021 Matthias Rosenthal * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/> ***********************************************************************/ #include "annotation_canvas.hpp" #include "wxMain.h" #include "utils/utils.hpp" #include <iostream> BEGIN_EVENT_TABLE(AnnotationCanvas, wxWindow) EVT_PAINT(AnnotationCanvas::OnPaint) END_EVENT_TABLE() AnnotationCanvas::AnnotationCanvas(Dis8051Frame* mainFrame, wxWindow *parent, wxWindowID id) : wxWindow(parent, id, wxDefaultPosition, wxSize(90, 300)) { this->mainFrame = mainFrame; } struct Jump { uint64_t from; uint64_t to; uint64_t getFirst() const { return std::min(from, to); } uint64_t getLast() const { return std::max(from, to); } }; void appendJump(uint64_t from, uint64_t to, std::vector<std::vector<Jump>> &jumps) { Jump newJump{from, to}; bool foundPlane = false; for(std::size_t iPlane = 0; iPlane < jumps.size(); iPlane++) { bool planeOk = true; for(const Jump &jump : jumps[iPlane]) { if((jump.getFirst() <= newJump.getLast()) && (jump.getLast() >= newJump.getFirst())) { planeOk = false; break; } } if(planeOk) { jumps[iPlane].push_back(newJump); foundPlane = true; break; } } if(!foundPlane) { jumps.push_back(std::vector<Jump>{newJump}); } } // this is because wxWidgets DC seems to have difficulties with integer values outside the 16-bit signed region inline int boundY(int val, int max) { if(val < -1000) { return -1000; } if(val > max+1000) { return max+1000; } return val; } void AnnotationCanvas::OnPaint(wxPaintEvent &event) { const int PLANE_MARGIN = 12; const int RIGHT_PLANE_MARGIN = 20; const int RIGHT_MARGIN = 2; const int ARROW_SIZE = 6; wxSize ownSize = GetSize(); wxPaintDC dc(this); int lineBegin, lineEnd; mainFrame->GetDisassemblyLinesOnScreen(&lineBegin, &lineEnd); auto itAddressBegin = mainFrame->getDisassembly()->addressByLine.find(lineBegin); auto itAddressEnd = mainFrame->getDisassembly()->addressByLine.find(lineEnd); if((itAddressBegin == mainFrame->getDisassembly()->addressByLine.end()) || (itAddressEnd == mainFrame->getDisassembly()->addressByLine.end())) { return; } uint64_t addressBegin = itAddressBegin->second; uint64_t addressEnd = itAddressEnd->second; auto itInstruction = mainFrame->getDisassembly()->instructions.begin(); while(itInstruction->first < addressBegin) { itInstruction++; if(itInstruction == mainFrame->getDisassembly()->instructions.end()) { return; } } std::vector<std::vector<Jump>> jumps; while(itInstruction->first < addressEnd) { if(itInstruction->second.isJump || itInstruction->second.isCondJump) { if(itInstruction->second.isCall()) { if(annotateCalls) { appendJump(itInstruction->first, itInstruction->second.address, jumps); } } else { appendJump(itInstruction->first, itInstruction->second.address, jumps); } } auto itTarget = mainFrame->getDisassembly()->jumpTargets.find(itInstruction->first); if(itTarget != mainFrame->getDisassembly()->jumpTargets.end()) { for(uint64_t sourceAddress : itTarget->second) { if((sourceAddress < addressBegin) || (sourceAddress >= addressEnd)) { // otherwise we get / got this also by parsing the instruction appendJump(sourceAddress, itInstruction->first, jumps); } } } itInstruction++; if(itInstruction == mainFrame->getDisassembly()->instructions.end()) { return; } } wxPen jumpForwardsPen(wxColour(50, 50, 255), 2); wxPen jumpBackwardsPen(wxColour(0, 0, 200), 2); for(std::size_t iPlane = 0; iPlane < jumps.size(); iPlane++) { for(Jump jump : jumps[iPlane]) { // TODO maybe too unperformant! int lineFrom = mainFrame->getDisassembly()->findLineByAddress(jump.from); int lineTo = mainFrame->getDisassembly()->findLineByAddress(jump.to); if(jump.from <= jump.to) { dc.SetPen(jumpForwardsPen); } else { // jump backwards dc.SetPen(jumpBackwardsPen); } int startX = ownSize.GetWidth() - RIGHT_MARGIN; int betweenX = ownSize.GetWidth() - RIGHT_PLANE_MARGIN - iPlane * PLANE_MARGIN; int fromY = boundY((lineFrom - lineBegin) * lineHeight + lineHeight / 2, ownSize.GetHeight()); int toY = boundY((lineTo - lineBegin) * lineHeight + lineHeight / 2, ownSize.GetHeight()); dc.DrawLine(startX, fromY, betweenX, fromY); dc.DrawLine(betweenX, fromY, betweenX, toY); dc.DrawLine(betweenX, toY, startX, toY); dc.DrawLine(startX - ARROW_SIZE, toY - ARROW_SIZE, startX, toY); dc.DrawLine(startX - ARROW_SIZE, toY + ARROW_SIZE, startX, toY); } } }
5,842
C++
.cpp
147
32.619048
111
0.625705
msrst/interactive-8051-disassembler
39
5
1
GPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,865
utils_wx.cpp
msrst_interactive-8051-disassembler/utils/utils_wx.cpp
/************************************************************************ * Copyright (C) 2020-2021 Matthias Rosenthal * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/> ***********************************************************************/ #include <iostream> #include "utils_wx.h" namespace utils { wxString Format_Defaultdate_wxString(long long int datum) { time_t sec = datum / 1000; long int ms = datum - ((long long int)sec) * 1000; char* c_datum = new char[100]; tm* tmZeit = localtime(&sec); std::strftime(c_datum, 100, "%d.%m.%Y %X", tmZeit); wxString ret = wxString(c_datum); if(ms >= 100) { #ifdef _WIN32 ret.append(wxString::Format(wxT(":%li"), ms)); // %i #else ret.append(wxString::Format(wxT(":%d"), (int)ms)); #endif } else if(ms >= 10) { #ifdef _WIN32 ret.append(wxString::Format(wxT(":0%li"), ms)); // %i #else ret.append(wxString::Format(wxT(":0%d"), (int)ms)); #endif } else { #ifdef _WIN32 ret.append(wxString::Format(wxT(":00%li"), ms)); // %i #else ret.append(wxString::Format(wxT(":00%d"), (int)ms)); #endif } delete c_datum; return ret; } } // namespace utils wxString fn_Char_To_wxUTF8String(uint32_t zeichen) { std::string stdstr = utils::Char_To_UTF8String(zeichen); return wxString::FromUTF8(stdstr.c_str(), stdstr.length()); } std::string fn_wxUTF8String_ToUTF8String(wxString string) { std::string stdstr; for(wxString::iterator it_char = string.begin(); it_char != string.end(); it_char++) { stdstr.append(utils::Char_To_UTF8String((*it_char).GetValue())); // (*it_char) ist ein Objekt vom Typ wxChar, wxChar ist wxUniChar, wxUniChar::GetValue() gibt wxUint32 zurück } return stdstr; } wxString fn_wxbuildinfo(wxbuildinfoformat format) { wxString wxbuild(wxVERSION_STRING); if (format == wxbuildinfof_long_f ) { #if defined(__WXMSW__) wxbuild << _T("-Windows"); #elif defined(__WXMAC__) wxbuild << _T("-Mac"); #elif defined(__UNIX__) wxbuild << _T("-Linux"); #endif #if wxUSE_UNICODE wxbuild << _T("-Unicode build"); #else wxbuild << _T("-ANSI build"); #endif // wxUSE_UNICODE } return wxbuild; }
2,845
C++
.cpp
87
28.609195
183
0.619949
msrst/interactive-8051-disassembler
39
5
1
GPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,866
logger.cpp
msrst_interactive-8051-disassembler/utils/logger.cpp
/************************************************************************ * Copyright (C) 2020-2021 Matthias Rosenthal * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/> ***********************************************************************/ #include <iostream> #include "logger.h" #include "../utils/utils.hpp" #ifdef LOGGER_WXTEXTCTRL #include "../utils/utils_wx.h" #endif #include <boost/thread/lock_guard.hpp> namespace logger { #ifdef LOGGER_WXTEXTCTRL void logdisplay_textctrl::newLine(message& msg) { switch(msg.type) { case message_type::error: m_textctrl->SetDefaultStyle(m_gui_palette->logger_textctrl_error_textattr); m_textctrl->AppendText(utils::Format_Defaultdate_wxString(msg.time) + wxT(": ") + wxString::FromUTF8(msg.messageString.c_str()) + wxT("\n")); m_textctrl->SetDefaultStyle(m_gui_palette->default_textctrl_textattr); break; case message_type::warning: m_textctrl->SetDefaultStyle(m_gui_palette->logger_textctrl_warning_textattr); m_textctrl->AppendText(utils::Format_Defaultdate_wxString(msg.time) + wxT(": ") + wxString::FromUTF8(msg.messageString.c_str()) + wxT("\n")); m_textctrl->SetDefaultStyle(m_gui_palette->default_textctrl_textattr); break; case message_type::information: m_textctrl->SetDefaultStyle(m_gui_palette->logger_textctrl_message_textattr); m_textctrl->AppendText(utils::Format_Defaultdate_wxString(msg.time) + wxT(": ") + wxString::FromUTF8(msg.messageString.c_str()) + wxT("\n")); m_textctrl->SetDefaultStyle(m_gui_palette->default_textctrl_textattr); break; } } #endif // LOGGER_WXTEXTCTRL void logdisplay_cout::newLine(message& msg) { switch(msg.type) { case message_type::error: std::cout << utils::Format_Defaultdate_stdString(msg.time) << " [error ]: " << msg.messageString << std::endl; break; case message_type::warning: std::cout << utils::Format_Defaultdate_stdString(msg.time) << " [warn ]: " << msg.messageString << std::endl; break; case message_type::information: std::cout << utils::Format_Defaultdate_stdString(msg.time) << " [inform]: " << msg.messageString << std::endl; break; } } logdisplay_file::logdisplay_file() { isFileOpen = false; } void logdisplay_file::beginUpdate() { file.open(filename.c_str(), std::ios_base::out | std::ios_base::app); // If the file already exists, we will append to it. Else, a new file is created. if(file) { isFileOpen = true; } else { // only cout to avoid endless recursion std::cout << "Logging error: File \"" << filename << "\" could not be opened. " << std::endl; } } void logdisplay_file::newLine(message& msg) { if(isFileOpen) { switch(msg.type) { case message_type::error: file << utils::Format_Defaultdate_stdString(msg.time) << " [error ]: " << msg.messageString << std::endl; break; case message_type::warning: file << utils::Format_Defaultdate_stdString(msg.time) << " [warn ]: " << msg.messageString << std::endl; break; case message_type::information: file << utils::Format_Defaultdate_stdString(msg.time) << " [inform]: " << msg.messageString << std::endl; break; } } } void logdisplay_file::endUpdate() { if(isFileOpen) { file.close(); isFileOpen = false; } } //----------------------------------------------------------------------------------------------------------------------------------- logger::logger() { // } logger::~logger() { for(std::list<logdisplay*>::iterator it_logdisplay = logdisplays.begin(); it_logdisplay != logdisplays.end();) { if(((*it_logdisplay)->type != logdisplay_type::file) && ((*it_logdisplay)->type != logdisplay_type::cout)) { delete *it_logdisplay; it_logdisplay = logdisplays.erase(it_logdisplay); } else { it_logdisplay++; } } updateLogDisplays(); // little bit unsafe, but to ensure logging.. for(std::list<logdisplay*>::iterator it_logdisplay = logdisplays.begin(); it_logdisplay != logdisplays.end(); it_logdisplay++) { delete *it_logdisplay; } } void logger::LogError(std::string msg) { message newMessage; newMessage.time = utils::GetTime_Milliseconds(); newMessage.type = message_type::error; newMessage.messageString = msg; registerMessage(newMessage); } void logger::LogWarning(std::string msg) { message newMessage; newMessage.time = utils::GetTime_Milliseconds(); newMessage.type = message_type::warning; newMessage.messageString = msg; registerMessage(newMessage); } void logger::LogInformation(std::string msg) { message newMessage; newMessage.time = utils::GetTime_Milliseconds(); newMessage.type = message_type::information; newMessage.messageString = msg; registerMessage(newMessage); } void logger::registerMessage(message &newMessage) { { boost::lock_guard<boost::mutex> locker(messagesLock); messages.push_back(newMessage); if(messages.size() > LOGGER_MAX_LOGS) { std::list<message>::iterator itMessage = messages.begin(); itMessage++; messages.erase(messages.begin(), itMessage); } } { boost::lock_guard<boost::mutex> locker(newMessagesLock); newMessages.push_back(newMessage); if(newMessages.size() > LOGGER_MAX_LOGS) { std::list<message>::iterator itMessage = newMessages.begin(); itMessage++; newMessages.erase(newMessages.begin(), itMessage); } } // propagate it immediately and do not wait for log display update std::cout << utils::Format_Defaultdate_stdString(newMessage.time) << (newMessage.type == message_type::error ? " [error ]: " : (newMessage.type == message_type::information ? " [inform]: " : " [warn ]: ")) << newMessage.messageString << std::endl; } #ifdef LOGGER_WXTEXTCTRL void logger::AddLogDisplay(wxTextCtrl* textctrl, gui_palette* c_gui_palette) { logdisplay_textctrl* newLogdisplay = new logdisplay_textctrl; newLogdisplay->type = logdisplay_type::textctrl; newLogdisplay->m_textctrl = textctrl; newLogdisplay->m_gui_palette = c_gui_palette; logdisplays.push_back(newLogdisplay); } #endif // LOGGER_WXTEXTCTRL void logger::AddLogDisplay_cout() { logdisplay_cout* newLogdisplay = new logdisplay_cout; newLogdisplay->type = logdisplay_type::cout; logdisplays.push_back(newLogdisplay); } void logger::AddLogDisplay(std::string dateiname) { logdisplay_file* newLogdisplay = new logdisplay_file; newLogdisplay->type = logdisplay_type::file; newLogdisplay->filename = dateiname; logdisplays.push_back(newLogdisplay); } void logger::updateLogDisplays() { std::list<message> newMessagesCopy; { boost::lock_guard<boost::mutex> locker(newMessagesLock); newMessagesCopy = newMessages; newMessages.clear(); } for(std::list<logdisplay*>::iterator it_logdisplay = logdisplays.begin(); it_logdisplay != logdisplays.end(); it_logdisplay++) { (*it_logdisplay)->beginUpdate(); for(std::list<message>::iterator itMessage = newMessagesCopy.begin(); itMessage != newMessagesCopy.end(); itMessage++) { (*it_logdisplay)->newLine(*itMessage); } (*it_logdisplay)->endUpdate(); } } } // namespace logger
8,387
C++
.cpp
219
31.968037
156
0.62932
msrst/interactive-8051-disassembler
39
5
1
GPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,867
utils.cpp
msrst_interactive-8051-disassembler/utils/utils.cpp
/************************************************************************ * Copyright (C) 2020-2021 Matthias Rosenthal * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/> ***********************************************************************/ #include <string> #include <sstream> #include <cmath> #include <iomanip> #include <unistd.h> #include <cstring> #include <istream> #include <iterator> #include <errno.h> #include <iostream> #include "utils.hpp" #ifdef __unix__ // für fn_DatumUebernehmen #include <utime.h> #endif // __unix__ #ifdef _WIN32 // both 32 and 64 bit #include <chrono> #endif // _WIN32 std::string fn_Int_To_StringU(uint64_t i) { if(i == 0) { return std::string("0"); } else { std::string ret; char zeichen; while(i != 0) { zeichen = static_cast<char>(i % 10) + 48; ret.insert(0, 1, zeichen); i /= 10; } return ret; } } std::string fn_Int_To_String(int64_t i) { if(i == 0) { return std::string("0"); } else { std::string ret; bool minuszeichen; if(i < 0) { i = 0 - i; minuszeichen = true; } else { minuszeichen = false; } char zeichen; while(i != 0) { zeichen = static_cast<char>(i % 10) + 48; ret.insert(0, 1, zeichen); i /= 10; } if(minuszeichen) { ret.insert(0, 1, '-'); } return ret; } } //------------------------------------------------------------------------------------------------------------------------- template<typename Tstr> std::string fn_FormatToHex(Tstr string, bool kleinbuchstaben) { std::string str_ret; typename Tstr::iterator it_zeichen = string.begin(); if(string.empty()) { return str_ret; } if(kleinbuchstaben) { uint8_t umwandlung = (((*it_zeichen) & 0xf0) >> 4); if(umwandlung > 9) { str_ret.append(1, 'a' - 10 + umwandlung); } else { str_ret.append(1, '0' + umwandlung); } umwandlung = (*it_zeichen) & 0x0f; if(umwandlung > 9) { str_ret.append(1, 'a' - 10 + umwandlung); } else { str_ret.append(1, '0' + umwandlung); } for(it_zeichen++; it_zeichen != string.end(); it_zeichen++) { str_ret.append(1, ' '); umwandlung = (((*it_zeichen) & 0xf0) >> 4); if(umwandlung > 9) { str_ret.append(1, 'a' - 10 + umwandlung); } else { str_ret.append(1, '0' + umwandlung); } umwandlung = (*it_zeichen) & 0x0f; if(umwandlung > 9) { str_ret.append(1, 'a' - 10 + umwandlung); } else { str_ret.append(1, '0' + umwandlung); } } } else { uint8_t umwandlung = (((*it_zeichen) & 0xf0) >> 4); if(umwandlung > 9) { str_ret.append(1, 'A' - 10 + umwandlung); } else { str_ret.append(1, '0' + umwandlung); } umwandlung = (*it_zeichen) & 0x0f; if(umwandlung > 9) { str_ret.append(1, 'A' - 10 + umwandlung); } else { str_ret.append(1, '0' + umwandlung); } for(it_zeichen++; it_zeichen != string.end(); it_zeichen++) { str_ret.append(1, ' '); umwandlung = (((*it_zeichen) & 0xf0) >> 4); if(umwandlung > 9) { str_ret.append(1, 'A' - 10 + umwandlung); } else { str_ret.append(1, '0' + umwandlung); } umwandlung = (*it_zeichen) & 0x0f; if(umwandlung > 9) { str_ret.append(1, 'A' - 10 + umwandlung); } else { str_ret.append(1, '0' + umwandlung); } } } return str_ret; } // Instantiations template std::string fn_FormatToHex(std::string string, bool kleinbuchstaben); template std::string fn_FormatToHex(std::basic_string<uint8_t> string, bool kleinbuchstaben); //----------------------------------------------------------------------------------------------------------------------- bool fn_str_begins_with(std::string str, std::string begin) { if(str.size() >= begin.size()) { for(unsigned int i1 = 0; i1 < begin.size(); i1++) { if(str[i1] != begin[i1]) { return false; } } return true; } else { return false; } } bool fn_str_ends_with(std::string str, std::string end) { if(str.size() >= end.size()) { unsigned int offset = str.size() - end.size(); for(unsigned int i1 = 0; i1 < end.size(); i1++) { if(str[i1+offset] != end[i1]) { return false; } } return true; } else { return false; } } void fn_str_replace_char(std::string &str, char suchen, std::string ersetzen) { for(unsigned int izeichen = 0; izeichen < str.length(); ) { if(str[izeichen] == suchen) { str.replace(izeichen, 1, ersetzen); izeichen += ersetzen.length(); } else { izeichen++; } } } //------------------------------------------------------------------------------------------------------------ namespace utils { //---------------------------------------------------------------------------------------------------------------------- uint8_t Hex_To_uint8(char hex1, char hex2) { uint8_t ret = 0; if((hex1 > 64) && (hex1 < 71)) //A-F { hex1 -= 65; hex1 += 10; } else if((hex1 > 96) && (hex1 < 103)) //a - f { hex1 -= 97; hex1 += 10; } else if((hex1 > 47) && (hex1 < 58)) //0-9 { hex1 -= 48; } else { return 0; } if((hex2 > 64) && (hex2 < 71)) //A-F { hex2 -= 65; hex2 += 10; } else if((hex2 > 96) && (hex2 < 103)) //a - f { hex2 -= 97; hex2 += 10; } else if((hex2 > 47) && (hex2 < 58)) //0-9 { hex2 -= 48; } else { return 0; } ret = hex2; ret += hex1 * 16; return ret; } std::string Format_Defaultdate_stdString(long long int datum, char ms_trennzeichen) { time_t sec = datum / 1000; long int ms = datum - ((long long int)sec) * 1000; char* c_datum = new char[100]; tm* tmZeit = std::localtime(&sec); std::strftime(c_datum, 100, "%d.%m.%Y %X", tmZeit); std::string ret(c_datum); delete c_datum; ret.append(1, ms_trennzeichen); if(ms >= 100) { } else if(ms >= 10) { ret.append("0"); } else { ret.append("00"); } ret.append(Int_To_String(ms)); return ret; } std::string Format_Sec_Standarddatum_stdString(time_t datum) { char c_datum[100]; tm* tmZeit = std::localtime(&datum); std::strftime(c_datum, 100, "%d.%m.%Y %X", tmZeit); return std::string(c_datum); } std::string Int_To_String(int64_t i) { if(i == 0) { return std::string("0"); } else { std::string ret; bool minuszeichen; if(i < 0) { i = 0 - i; minuszeichen = true; } else { minuszeichen = false; } char zeichen; while(i != 0) { zeichen = static_cast<char>(i % 10) + 48; ret.insert(0, 1, zeichen); i /= 10; } if(minuszeichen) { ret.insert(0, 1, '-'); } return ret; } } std::string Int_To_String_Zeros(long long int i, unsigned long int breite) { if(i == 0) { return std::string(breite, '0'); } else { std::string ret; bool minuszeichen; if(i < 0) { i = 0 - i; minuszeichen = true; } else { minuszeichen = false; } char zeichen; while(i != 0) { long long int i_durch_10 = i / 10; zeichen = i - i_durch_10 * 10 + 48; ret.insert(0, 1, zeichen); i = i_durch_10; } if(minuszeichen) { int anzahl_vornullen = ((int)breite) - ((int)ret.size()) - 1; if(anzahl_vornullen > 0) { ret.insert(0, anzahl_vornullen, '0'); } ret.insert(0, 1, '-'); } else { int anzahl_vornullen = ((int)breite) - ((int)ret.size()); if(anzahl_vornullen > 0) { ret.insert(0, anzahl_vornullen, '0'); } } return ret; } } std::string Int_To_String_Hex(int64_t i, bool lowercase) { if(i == 0) { return std::string("0"); } else { std::string ret; bool minuszeichen; if(i < 0) { i = 0 - i; minuszeichen = true; } else { minuszeichen = false; } char zeichen; while(i != 0) { zeichen = static_cast<char>(i % 16) + 48; if(zeichen > '9') { zeichen += (lowercase ? 'a' : 'A') - '9' - 1; } ret.insert(0, 1, zeichen); i /= 16; } if(minuszeichen) { ret.insert(0, 1, '-'); } return ret; } } //----------------------------------------------------------------------------------------------------------------------- string_to_int_converter::string_to_int_converter() { Init(); } void string_to_int_converter::Init() { fehler = 0; } long long int string_to_int_converter::ConvertToLLI(std::string rohstring) { return ConvertToLLIFromSIt(rohstring.begin(), rohstring.end()); } long long int string_to_int_converter::ConvertToLLI_Hex(std::string rohstring) { return ConvertToLLIFromSIt_Hex(rohstring.begin(), rohstring.end()); } long long int string_to_int_converter::ConvertToLLI_HexOk(std::string rohstring) { return ConvertToLLIFromSIt_HexOk(rohstring.begin(), rohstring.end()); } long long int string_to_int_converter::ConvertToLLIFromSIt(std::string::iterator begin, std::string::iterator end) { if(begin == end) { fehler++; return 0; } else { long long int ret = 0; std::string::iterator it_zeichen = begin; bool negativ; if(*it_zeichen == '-') { negativ = true; it_zeichen++; if(it_zeichen == end) { fehler++; return 0; } } else if(*it_zeichen == '+') { negativ = false; if(it_zeichen == end) { fehler++; return 0; } } else { negativ = false; } for(; it_zeichen != end; it_zeichen++) { long long int neue_ziffer = (*it_zeichen) - '0'; if((neue_ziffer < 0) || (neue_ziffer > 9)) { fehler++; return 0; } ret = ret * 10 + neue_ziffer; } if(negativ) { return 0 - ret; } else { return ret; } } } long long int string_to_int_converter::ConvertToLLIFromSIt_Hex(std::string::iterator begin, std::string::iterator end) { if(begin == end) { fehler++; return 0; } else { long long int ret = 0; for(std::string::iterator it_zeichen = begin; it_zeichen != end; it_zeichen++) { ret <<= 4; if((*it_zeichen >= '0') && (*it_zeichen <= '9')) { ret |= (long long int)((*it_zeichen) - '0') & 0x0f; } else if((*it_zeichen >= 'A') && (*it_zeichen <= 'F')) { ret |= (long long int)((*it_zeichen) - 55) & 0x0f; // 'A' ist Nr. 65 } else if((*it_zeichen >= 'a') && (*it_zeichen <= 'f')) { ret |= (long long int)((*it_zeichen) - 87) & 0x0f; // 'a' ist Nr. 97 } else { fehler++; return 0; } } return ret; } } long long int string_to_int_converter::ConvertToLLIFromSIt_HexOk(std::string::iterator begin, std::string::iterator end) { if(begin == end) { fehler++; return 0; } else { long long int ret = 0; if(*begin == '0') { begin++; if(*begin == 'x') { begin++; if(begin == end) { fehler++; return 0; } for(std::string::iterator it_zeichen = begin; it_zeichen != end; it_zeichen++) { ret <<= 4; if((*it_zeichen >= '0') && (*it_zeichen <= '9')) { ret |= (long long int)((*it_zeichen) - '0') & 0x0f; } else if((*it_zeichen >= 'A') && (*it_zeichen <= 'F')) { ret |= (long long int)((*it_zeichen) - 55) & 0x0f; // 'A' ist Nr. 65 } else if((*it_zeichen >= 'a') && (*it_zeichen <= 'f')) { ret |= (long long int)((*it_zeichen) - 87) & 0x0f; // 'a' ist Nr. 97 } else { fehler++; return 0; } } return ret; } else { begin--; } } std::string::iterator it_zeichen = begin; bool negativ; if(*it_zeichen == '-') { negativ = true; it_zeichen++; if(it_zeichen == end) { fehler++; return 0; } } else if(*it_zeichen == '+') { negativ = false; if(it_zeichen == end) { fehler++; return 0; } } else { negativ = false; } for(; it_zeichen != end; it_zeichen++) { long long int neue_ziffer = (*it_zeichen) - '0'; if((neue_ziffer < 0) || (neue_ziffer > 9)) { fehler++; return 0; } ret = ret * 10 + neue_ziffer; } if(negativ) { return 0 - ret; } else { return ret; } } } long long int string_to_int_converter::ConvertToLLIFromSIt(std::string::iterator begin, std::string::iterator end, char tausender_zeichen) { if(begin == end) { fehler++; return 0; } else { long long int ret = 0; std::string::iterator it_zeichen = begin; bool negativ; if(*it_zeichen == '-') { negativ = true; it_zeichen++; if(it_zeichen == end) { fehler++; return 0; } } else if(*it_zeichen == '+') { negativ = false; if(it_zeichen == end) { fehler++; return 0; } } else { negativ = false; } for(; it_zeichen != end; it_zeichen++) { if(*it_zeichen != tausender_zeichen) { long long int neue_ziffer = (*it_zeichen) - '0'; if((neue_ziffer < 0) || (neue_ziffer > 9)) { fehler++; return 0; } ret = ret * 10 + neue_ziffer; } } if(negativ) { return 0 - ret; } else { return ret; } } } double string_to_int_converter::ConvertToDouble(std::string rohstring, char punct_char, char tausender_zeichen) { return ConvertToDoubleFromSIt(rohstring.begin(), rohstring.end(), punct_char, tausender_zeichen); } double string_to_int_converter::ConvertToDoubleR(std::string rohstring, char punct_char, char tausender_zeichen) { return ConvertToDoubleRFromSIt(rohstring.begin(), rohstring.end(), punct_char, tausender_zeichen); } double string_to_int_converter::ConvertToDoubleFromSIt(std::string::iterator begin, std::string::iterator end, char punct_char, char tausender_zeichen) { if(begin == end) { fehler++; return 0; } else { double ret = 0; std::string::iterator it_zeichen = begin; bool negativ; if(*it_zeichen == '-') { negativ = true; it_zeichen++; if(it_zeichen == end) { fehler++; return 0; } } else if(*it_zeichen == '+') { negativ = false; if(it_zeichen == end) { fehler++; return 0; } } else { negativ = false; } for(; it_zeichen != end; it_zeichen++) { if(*it_zeichen == punct_char) { double kommastelle_fac = 1; for(it_zeichen++; it_zeichen != end; it_zeichen++) { if(*it_zeichen == 'e') { it_zeichen++; if(it_zeichen == end) { fehler++; return 0; } else { if(*it_zeichen == '+') { it_zeichen++; ret *= std::pow(10, ConvertToLLIFromSIt(it_zeichen, end)); } else if(*it_zeichen == '-') { it_zeichen++; ret *= std::pow(0.1, ConvertToLLIFromSIt(it_zeichen, end)); } else { fehler++; return 0; } } break; } else { kommastelle_fac *= 0.1; ret = ret + ((double)((*it_zeichen) - '0')) * kommastelle_fac; } } break; } else if(*it_zeichen == 'e') { it_zeichen++; if(it_zeichen == end) { fehler++; return 0; } else { if(*it_zeichen == '+') { it_zeichen++; ret *= std::pow(10, ConvertToLLIFromSIt(it_zeichen, end)); } else if(*it_zeichen == '-') { it_zeichen++; ret *= std::pow(0.1, ConvertToLLIFromSIt(it_zeichen, end)); } else { fehler++; return 0; } } break; } else if(*it_zeichen != tausender_zeichen) { double neue_ziffer = (*it_zeichen) - '0'; if((neue_ziffer < 0) || (neue_ziffer > 9)) { fehler++; return 0; } ret = ret * 10 + neue_ziffer; } } if(negativ) { return 0 - ret; } else { return ret; } } } double string_to_int_converter::ConvertToDoubleRFromSIt(std::string::iterator begin, std::string::iterator end, char punct_char, char tausender_zeichen) { std::string::iterator it_slash; for(it_slash = begin; it_slash != end; it_slash++) { if(*it_slash == '/') { break; } } if(it_slash == end) { return ConvertToDoubleFromSIt(begin, end, punct_char, tausender_zeichen); } else { long long int zaehler = ConvertToLLIFromSIt(begin, it_slash); it_slash++; long long int nenner = ConvertToLLIFromSIt(it_slash, end); if(nenner == 0) { fehler++; return 0; } else { return double(zaehler) / nenner; } } } bool string_to_int_converter::MistakeHappened() { return (fehler != 0); } //----------------------------------------------------------------------------------------------------------------------- string_to_int_limited_converter::string_to_int_limited_converter() { Init(); } void string_to_int_limited_converter::Init() { limitfehler = 0; } long long int string_to_int_limited_converter::ConvertToLLI_Limited(std::string rohstring, long long int min, long long int max) { return ConvertToLLIFromSIt_Limited(rohstring.begin(), rohstring.end(), min, max); } long long int string_to_int_limited_converter::ConvertToLLI_Hex_Limited(std::string rohstring, long long int min, long long int max) { return ConvertToLLIFromSIt_Hex_Limited(rohstring.begin(), rohstring.end(), min, max); } long long int string_to_int_limited_converter::ConvertToLLI_HexOk_Limited(std::string rohstring, long long int min, long long int max) { return ConvertToLLIFromSIt_HexOk_Limited(rohstring.begin(), rohstring.end(), min, max); } long long int string_to_int_limited_converter::ConvertToLLIFromSIt_Limited(std::string::iterator begin, std::string::iterator end, long long int min, long long int max) { long long int pruef = ConvertToLLIFromSIt(begin, end); if(pruef < min) { pruef = min; limitfehler++; } else if(pruef > max) { pruef = max; limitfehler++; } return pruef; } long long int string_to_int_limited_converter::ConvertToLLIFromSIt_Hex_Limited(std::string::iterator begin, std::string::iterator end, long long int min, long long int max) { long long int pruef = ConvertToLLIFromSIt_Hex(begin, end); if(pruef < min) { pruef = min; limitfehler++; } else if(pruef > max) { pruef = max; limitfehler++; } return pruef; } long long int string_to_int_limited_converter::ConvertToLLIFromSIt_HexOk_Limited(std::string::iterator begin, std::string::iterator end, long long int min, long long int max) { long long int pruef = ConvertToLLIFromSIt_HexOk(begin, end); if(pruef < min) { pruef = min; limitfehler++; } else if(pruef > max) { pruef = max; limitfehler++; } return pruef; } double string_to_int_limited_converter::ConvertToDouble_Limited(std::string rohstring, double min, double max, char punct_char, char tausender_zeichen) { double pruef = ConvertToDouble(rohstring, punct_char, tausender_zeichen); if(pruef < min) { pruef = min; limitfehler++; } else if(pruef > max) { pruef = max; limitfehler++; } return pruef; } double string_to_int_limited_converter::ConvertToDoubleR_Limited(std::string rohstring, double min, double max, char punct_char, char tausender_zeichen) { double pruef = ConvertToDoubleR(rohstring, punct_char, tausender_zeichen); if(pruef < min) { pruef = min; limitfehler++; } else if(pruef > max) { pruef = max; limitfehler++; } return pruef; } bool string_to_int_limited_converter::LimitMistakeHappened() { return (limitfehler != 0); } //----------------------------------------------------------------------------------------------------------------------- bool GetFileString(std::string dateiname, std::string* value, bool binary) { std::ifstream datei_istream; if(binary) { datei_istream.open(dateiname.c_str(), std::ios_base::in | std::ios_base::binary); } else { datei_istream.open(dateiname.c_str(), std::ios_base::in); } if(datei_istream) { datei_istream.unsetf(std::ios::skipws); // No white space skipping! value->clear(); std::copy( std::istream_iterator<char>(datei_istream), std::istream_iterator<char>(), // allgemeiner End-Iterator std::back_inserter(*value)); // dieser Iterator ist keine Referenz. Stattdessen ruft er bei einer // Zuweisung (*value).push_back(.) auf und macht nichts, wenn it++ aufgerufen wird. return true; } else { return false; } } bool SetFileString(std::string dateiname, const std::string &value) { std::ofstream datei_ostream; datei_ostream.open(dateiname.c_str(), std::ios_base::out | std::ios_base::binary); if(datei_ostream) { datei_ostream.write(value.c_str(), value.length()); return true; } else { return false; } } bool str_begins_with(const std::string &str, const std::string &begin) { if(str.size() >= begin.size()) { for(unsigned int i1 = 0; i1 < begin.size(); i1++) { if(str[i1] != begin[i1]) { return false; } } return true; } else { return false; } } bool str_ends_with(const std::string &str, const std::string &end) { if(str.size() >= end.size()) { unsigned int offset = str.size() - end.size(); for(unsigned int i1 = 0; i1 < end.size(); i1++) { if(str[i1+offset] != end[i1]) { return false; } } return true; } else { return false; } } void str_replace_char(std::string &str, char suchen, std::string ersetzen) { for(unsigned int izeichen = 0; izeichen < str.length(); ) { if(str[izeichen] == suchen) { str.replace(izeichen, 1, ersetzen); izeichen += ersetzen.length(); } else { izeichen++; } } } std::vector<std::string> str_split(const std::string &str, const std::string &split) { std::vector<std::string> splits; if(split.empty()) { std::cout << "Warnung: str_split: split = \"\"." << std::endl; splits.push_back(split); return splits; } std::size_t splitstr_begin = 0; do { std::size_t splitstr_end = str.find(split, splitstr_begin); if(splitstr_end == std::string::npos) { splits.push_back(str.substr(splitstr_begin, str.size() - splitstr_begin)); // Den Rest anhängen return splits; } else { splits.push_back(str.substr(splitstr_begin, splitstr_end - splitstr_begin)); // substr(pos, laenge) splitstr_begin = splitstr_end + split.size(); } } while(splitstr_begin != str.size()); return splits; } #define FN_STR_ISWHITE(zeichen) ((zeichen == ' ') || (zeichen == '\t') || (zeichen == '\n') || (zeichen == '\r')) std::string str_remove_sidewhites(const std::string &text) { if(text.empty()) { return text; } unsigned int begin, last; for(begin = 0; begin < text.length(); begin++) { if(!FN_STR_ISWHITE(text[begin])) { break; } } for(last = text.length() - 1; last > 0; last--) { if(!FN_STR_ISWHITE(text[last])) { break; } } if((last == 0) && FN_STR_ISWHITE(text[0])) { return std::string(); } return text.substr(begin, last - begin + 1); } std::string str_to_upper(std::string str) { bool b_umlaut = false; for(std::string::iterator it_zeichen = str.begin(); it_zeichen != str.end(); it_zeichen++) { if((*it_zeichen >= 'a') && (*it_zeichen <= 'z')) { *it_zeichen = *it_zeichen - 'a' + 'A'; } else if(*it_zeichen == '\xc3') { b_umlaut = true; } else if(b_umlaut) { if(*it_zeichen == '\xa4') { // ä *it_zeichen = '\x84'; } else if(*it_zeichen == '\xb6') { // ö *it_zeichen = '\x96'; } else if(*it_zeichen == '\xbc') { // ü *it_zeichen = '\x9c'; } b_umlaut = false; } } return str; } bool str_replace_one(std::string &str, const std::string &search, const std::string &replace) { std::size_t pos = str.find(search); if(pos == std::string::npos) { return false; } else { str.replace(pos, search.length(), replace); return true; } } std::string vectorstring_unsplit(const std::vector<std::string> &array, char zeichen) { if(array.empty()) { return std::string(); } std::string ret = array[0]; for(unsigned int i1 = 1; i1 < array.size(); i1++) { ret.append(1, zeichen); ret.append(array[i1]); } return ret; } //----------------------------------------------------------------------------------------------------------------------- void Char_To_UTF8String(uint32_t zeichen, std::string* str_ret) { // siehe de.wikipedia.org/wiki/UTF-8 if(zeichen >= 2097152) { // invalid characters str_ret->append("err"); } else if(zeichen >= 65536) { str_ret->append(1, 0xf0 | ((zeichen >> 18) & 0x07)); // 0xf0 = 1111 0000; 0x07 = 0000 0111 str_ret->append(1, 0x80 | ((zeichen >> 12) & 0x3F)); // 0x80 = 1000 0000; 0x3F = 0011 1111 str_ret->append(1, 0x80 | ((zeichen >> 6) & 0x3F)); // 0x80 = 1000 0000; 0x3F = 0011 1111 str_ret->append(1, 0x80 | (zeichen & 0x3F)); // 0x80 = 1000 0000; 0x3F = 0011 1111 } else if(zeichen >= 2048) { str_ret->append(1, 0xe0 | ((zeichen >> 12) & 0x0F)); // 0xe0 = 1110 0000; 0x0F = 0000 1111 str_ret->append(1, 0x80 | ((zeichen >> 6) & 0x3F)); // 0x80 = 1000 0000; 0x3F = 0011 1111 str_ret->append(1, 0x80 | (zeichen & 0x3F)); // 0x80 = 1000 0000; 0x3F = 0011 1111 } else if(zeichen >= 128) { str_ret->append(1, 0xc0 | ((zeichen >> 6) & 0x1F)); // 0xc0 = 1100 0000; 0x1F = 0001 1111 str_ret->append(1, 0x80 | (zeichen & 0x3F)); // 0x80 = 1000 0000; 0x3F = 0011 1111 //std::cout << int32_t(str_ret[0]) << " " << int32_t(str_ret[1]) << std::endl; } else { str_ret->append(1, zeichen); } } std::string Char_To_UTF8String(uint32_t zeichen) { std::string ret; Char_To_UTF8String(zeichen, &ret); return ret; } //----------------------------------------------------------------------------------------------------------------------- uint64_t GetTime_Microseconds() { // clock_gettime kommt von pthread -> bei Windows nicht benutzbar #ifdef _WIN32 //return clock() * 1000; return std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::steady_clock::now().time_since_epoch()).count(); #else struct timespec ts; clock_gettime(CLOCK_REALTIME, &ts); return ((uint64_t)(ts.tv_sec))*1000000 + ((uint64_t)(ts.tv_nsec/1000)); #endif } long long int GetTime_Milliseconds() { // clock_gettime kommt von pthread -> bei Windows nicht benutzbar #ifdef _WIN32 //return clock() * 1000; return std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count(); #else struct timespec ts; clock_gettime(CLOCK_REALTIME, &ts); return ((long long int)(ts.tv_sec))*1000 + ((long long int)(ts.tv_nsec/1000000)); #endif } double GetTimeAsDouble() { return double(GetTime_Microseconds()) / 1000000; } double GetClockAsDouble() { static uint64_t start_zeit = GetTime_Microseconds(); return double(GetTime_Microseconds() - start_zeit) / 1000000; } int32_t GetClock_Milliseconds_I32() { static long long int start_zeit = GetTime_Milliseconds(); return int32_t(GetTime_Milliseconds() - start_zeit); } } // namespace utils
32,181
C++
.cpp
1,065
21.876995
175
0.49017
msrst/interactive-8051-disassembler
39
5
1
GPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,868
gui_palette.cpp
msrst_interactive-8051-disassembler/gui/gui_palette.cpp
/************************************************************************ * Copyright (C) 2020-2021 Matthias Rosenthal * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/> ***********************************************************************/ #include "wx/wx.h" #include "wx/image.h" #include "wx/imagxpm.h" #include "../consts.hpp" #include "gui_palette.h" void gui_palette_init(gui_palette& gui_palette) { wxMemoryDC dummydc; wxSize knopfbmp_standardsize; gui_palette.textextent_teststring = wxT("AaZz\x00e4")wxT("0?*#',;.()$"); gui_palette.backgroundcolour_frame = wxColour(230, 230, 230); gui_palette.backgroundcolour_frame_pen = wxPen(gui_palette.backgroundcolour_frame, 1, wxPENSTYLE_SOLID); gui_palette.backgroundcolour_frame_brush = wxBrush(gui_palette.backgroundcolour_frame); gui_palette.logger_textctrl_error_textattr = wxTextAttr(*wxRED, *wxWHITE); gui_palette.logger_textctrl_warning_textattr = wxTextAttr(wxColour(255, 160, 0), *wxWHITE); gui_palette.logger_textctrl_message_textattr = wxTextAttr(wxColour(31, 75, 147), *wxWHITE); gui_palette.default_textctrl_textattr = wxTextAttr(*wxBLACK, *wxWHITE); } void gui_palette_end(gui_palette& c_gui_palette) { // }
1,827
C++
.cpp
37
45.459459
109
0.676421
msrst/interactive-8051-disassembler
39
5
1
GPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,869
switch_statement.cpp
msrst_interactive-8051-disassembler/8051/switch_statement.cpp
/************************************************************************ * Copyright (C) 2020-2021 Matthias Rosenthal * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/> ***********************************************************************/ #include "switch_statement.hpp" #include "../utils/utils.hpp" namespace disas8051 { std::string SwitchStatement::ValuesCase::formatValues() { std::string valuesStr; for(int32_t value : values) { if(!valuesStr.empty()) { valuesStr += ","; } if(value == DEFAULT_CASE_VALUE) { valuesStr += "default"; } else { valuesStr += "0x" + utils::Int_To_String_Hex(value); } } return valuesStr; } std::vector<SwitchStatement::ValuesCase> SwitchStatement::groupCasesByValues() const { std::vector<ValuesCase> valuesCases; for(Case caseBlock : cases) { bool valuesCaseFound = false; for(ValuesCase valuesCase : valuesCases) { if(valuesCase.address == caseBlock.address) { valuesCase.values.push_back(caseBlock.value); valuesCaseFound = true; break; } } if(!valuesCaseFound) { valuesCases.emplace_back(caseBlock.value, caseBlock.address); } } return valuesCases; } } // namespace disas8051
1,810
C++
.cpp
52
30.942308
85
0.657061
msrst/interactive-8051-disassembler
39
5
1
GPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,870
disassembly.cpp
msrst_interactive-8051-disassembler/8051/disassembly.cpp
/************************************************************************ * Copyright (C) 2020-2021 Matthias Rosenthal * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/> ***********************************************************************/ #include <cctype> #include "wx/stc/stc.h" #include "../utils/utils.hpp" #include "disassembly.hpp" #include "disassembler.hpp" namespace disas8051 { std::string readLineWithoutPreWhitespaces(std::istream &istream) { char buf[256]; while(std::isspace(istream.peek())) { istream.get(); } istream.getline(buf, 256); std::string str(buf); if(str.empty()) { return str; } else { // do not store \r in the string on linux (on windows, \r\n is automatically converted to \n) if(str[str.length() - 1] == '\r') { return str.substr(0, str.length() - 1); } else { return str; } } } void AppendBufAddress(wxStyledTextCtrl *textCtrl, uint64_t address) { wxString text = wxString::Format(wxT("%5x "), (int)address); textCtrl->AppendText(text); textCtrl->SetStyling(text.length(), (int)Styles::BUF_ADDRESS); } void InsertBufAddress(wxStyledTextCtrl *textCtrl, int pos, uint64_t address) { wxString text = wxString::Format(wxT("%5x "), (int)address); textCtrl->InsertText(pos, text); textCtrl->SetStyling(text.length(), (int)Styles::BUF_ADDRESS); } void Disassembly::printToWx(wxStyledTextCtrl *textCtrl) { this->textCtrl = textCtrl; addressByLine.clear(); TEXTCTRL_START_STYLING(textCtrl, textCtrl->GetTextLength()); int undefinedBytes = 0; int currentLine = 0; for(uint64_t bufAddr = 0; bufAddr < buf.length(); bufAddr++) { auto it = instructions.find(bufAddr); if(it == instructions.end()) { if((undefinedBytes > 0) && (bufAddr % 16 == 0)) { textCtrl->AppendText("\n"); addressByLine[currentLine] = bufAddr - undefinedBytes; currentLine++; textCtrl->SetStyling(undefinedBytes * 3 + 1, (int)Styles::BYTES); undefinedBytes = 0; } if(undefinedBytes == 0) { AppendBufAddress(textCtrl, bufAddr); } textCtrl->AppendText(wxString::FromUTF8((fn_FormatToHex(buf.substr(bufAddr, 1), true) + ' ').c_str())); undefinedBytes++; } else { if(undefinedBytes) { textCtrl->AppendText("\n"); addressByLine[currentLine] = bufAddr - undefinedBytes; currentLine++; textCtrl->SetStyling(undefinedBytes * 3 + 1, (int)Styles::BYTES); undefinedBytes = 0; } AppendBufAddress(textCtrl, bufAddr); it->second.printToWx(textCtrl); addressByLine[currentLine] = bufAddr; currentLine++; bufAddr += it->second.length - 1; // -1 because its incremented by the for loop textCtrl->AppendText(wxT("\n")); textCtrl->SetStyling(1, (int)Styles::DEFAULT); int iSwitchStatement = findSwitchStatementOnExact(it->first); if(iSwitchStatement >= 0) { bufAddr = it->first + it->second.length; std::vector<SwitchStatement::ValuesCase> valuesCases = switchStatements[(std::size_t)iSwitchStatement].groupCasesByValues(); for(SwitchStatement::ValuesCase valuesCase : valuesCases) { AppendBufAddress(textCtrl, bufAddr); std::string str = "case " + valuesCase.formatValues() + ": goto " + formatWithFunction(valuesCase.address); textCtrl->AppendText(wxString::FromUTF8(str.c_str())); textCtrl->SetStyling(str.length(), (int)Styles::DEFAULT); addressByLine[currentLine] = bufAddr; currentLine++; textCtrl->AppendText(wxT("\n")); textCtrl->SetStyling(1, (int)Styles::DEFAULT); } bufAddr += switchStatements[iSwitchStatement].getDataLength() - 1; // -1 because its incremented by the for loop } } } textCtrl->SetStyling(undefinedBytes * 3, (int)Styles::BYTES); addressByLine[currentLine] = buf.length() - undefinedBytes; } int Disassembly::findLineByAddress(int address) { if((address < 0) || ((std::size_t)address >= buf.length())) { return -1; } for(auto it = addressByLine.begin(); it != addressByLine.end(); it++) { if(it->second >= (uint64_t)address) { return it->first; } } return -1; } int Disassembly::openMetaFile(std::string filename) { std::ifstream istream(filename); if(!istream) { return -1; } std::string str; utils::string_to_int_limited_converter convertobj; int line = 0; while(true) { line++; istream >> str; if(istream.eof()) { break; } uint64_t address = convertobj.ConvertToLLI_Hex_Limited(str, 0, std::numeric_limits<long long int>::max()); if(convertobj.MistakeHappened() || convertobj.LimitMistakeHappened()) { logger->LogError("file " + filename + " contains an invalid address on line " + std::to_string(line + 1)); return -2; } istream >> str; if((str == "itr") || (str == "fnc")) { Function fnc; fnc.isInterrupt = (str == "itr"); istream >> str; if(str == "shown") { fnc.isShownInGraph = true; } else if(str == "hidden") { fnc.isShownInGraph = false; } else { logger->LogError("file " + filename + " contains an invalid shown/hidden value on line " + std::to_string(line + 1)); istream.close(); return -2; } istream >> str; fnc.posX = (int)convertobj.ConvertToLLI_Limited(str, -15000, 15000); istream >> str; fnc.posY = (int)convertobj.ConvertToLLI_Limited(str, -15000, 15000); if(convertobj.MistakeHappened() || convertobj.LimitMistakeHappened()) { logger->LogError("file " + filename + " contains an invalid position on line " + std::to_string(line + 1)); istream.close(); return -2; } str = readLineWithoutPreWhitespaces(istream); fnc.name = str; if(functions.find(address) != functions.end()) { logger->LogWarning("file " + filename + " line " + std::to_string(line + 1) + ": Multiple definitions for function on address " + std::to_string(address) + ", using last one."); } functions[address] = fnc; } else if(str == "cmt") { str = readLineWithoutPreWhitespaces(istream); auto itComment = pendingComments.find(address); if(itComment == pendingComments.end()) { pendingComments[address] = str; } else { itComment->second += str; } } else if(str == "rcl") { auto itRemapCall = remapCalls.find(address); if(itRemapCall != remapCalls.end()) { logger->LogWarning("file " + filename + " line " + std::to_string(line + 1) + ": Multiple definitions for remap call on address " + std::to_string(address) + ", using last one."); } remapCalls[address] = RemapCall{}; } else if(str == "ign") { auto itIgnoreBlock = ignoreBlocks.find(address); if(itIgnoreBlock != ignoreBlocks.end()) { logger->LogWarning("file " + filename + " line " + std::to_string(line + 1) + ": Multiple definitions for ignore on address " + std::to_string(address) + ", using last one."); } ignoreBlocks[address] = IgnoreBlock{}; } else { logger->LogError("file " + filename + " line " + std::to_string(line + 1) + ": Invalid type \"" + str + '"'); istream.close(); return -2; } } istream.close(); return 0; } int Disassembly::saveMetaFile(std::string filename) { std::ofstream ostream(filename, std::ios_base::out); if(!ostream) { return -1; } for(const auto &pair : instructions) { if(!pair.second.comment.empty()) { std::string address = utils::Int_To_String_Hex(pair.first); ostream << std::string(5 - address.length(), ' ') << address << " cmt " << pair.second.comment << std::endl; } } for(const auto &pair : functions) { std::string address = utils::Int_To_String_Hex(pair.first); ostream << std::string(5 - address.length(), ' ') << address; ostream << (pair.second.isInterrupt ? " itr " : " fnc "); ostream << (pair.second.isShownInGraph ? "shown " : "hidden "); ostream << pair.second.posX << " " << pair.second.posY << " " << pair.second.name << std::endl; } for(const auto &pair : remapCalls) { std::string address = utils::Int_To_String_Hex(pair.first); ostream << std::string(5 - address.length(), ' ') << address << " rcl" << std::endl; } for(const auto &pair : ignoreBlocks) { std::string address = utils::Int_To_String_Hex(pair.first); ostream << std::string(5 - address.length(), ' ') << address << " ign" << std::endl; } ostream.close(); return 0; } void Disassembly::resolveRemapCalls(Disassembler *disassembler) { for(auto &pair : remapCalls) { auto itInstruction = instructions.find(pair.first); if(itInstruction == instructions.end()) { disassembler->followCodePath(buf, pair.first, this); itInstruction = instructions.find(pair.first); } if(itInstruction->second.getName() != "MOV DPTR, ") { logger->LogWarning("Skipped RemapCall on address " + utils::Int_To_String_Hex(pair.first) + " because it does not start with a MOV DPTR instruction."); pair.second.targetAddress = -1; continue; } pair.second.targetAddress = itInstruction->second.arg1; uint64_t nextAddress = itInstruction->first + itInstruction->second.length; itInstruction++; if(itInstruction->first != nextAddress) { logger->LogWarning("Skipped RemapCall on address " + utils::Int_To_String_Hex(pair.first) + " because MOV DPTR instruction is not directly followed by another instruction."); pair.second.targetAddress = -1; continue; } if(!itInstruction->second.isJump) { logger->LogWarning("Skipped RemapCall on address " + utils::Int_To_String_Hex(pair.first) + " because second instruction is not a jump."); pair.second.targetAddress = -1; continue; } auto itFunction = functions.find(itInstruction->second.address); if(itFunction == functions.end()) { logger->LogWarning("Skipped RemapCall on address " + utils::Int_To_String_Hex(pair.first) + " because second instruction does not jump to a named function."); pair.second.targetAddress = -1; continue; } int iOffsetBegin = itFunction->second.name.length() - 1; while((iOffsetBegin >= 0) && utils::is_hexchar(itFunction->second.name[iOffsetBegin])) { iOffsetBegin--; } utils::string_to_int_converter convertobj; pair.second.targetAddress += convertobj.ConvertToLLI_Hex(itFunction->second.name.substr( iOffsetBegin + 1, itFunction->second.name.length() - 1 - iOffsetBegin)); if(convertobj.MistakeHappened()) { logger->LogWarning("Skipped RemapCall on address " + utils::Int_To_String_Hex(pair.first) + " because second instruction jump to a function without a valid hex address at the end of its name."); pair.second.targetAddress = -1; continue; } std::cout << "jump to " + utils::Int_To_String_Hex(pair.second.targetAddress) << std::endl; if(instructions.find(pair.second.targetAddress) == instructions.end()) { logger->LogInformation("Remap Call on address " + utils::Int_To_String_Hex(pair.first) + " to address " + utils::Int_To_String_Hex(pair.second.targetAddress) + ": Disassembling target code."); disassembler->followCodePath(buf, pair.second.targetAddress, this); } } } void Disassembly::resolveComments() { for(auto itComment = pendingComments.begin(); itComment != pendingComments.end(); itComment++) { auto itInstruction = instructions.find(itComment->first); if(itInstruction == instructions.end()) { logger->LogWarning("Address " + utils::Int_To_String_Hex(itComment->first) + " for comment \"" + itComment->second + "\" could not be resolved to an instruction."); } else { itInstruction->second.comment += itComment->second; } } } struct RegisterArea { int addressFirst; int addressLast; int size; // is checked const char *name; bool contains(int address) { return (address >= addressFirst) && (address <= addressLast); } }; static RegisterArea registerAreas[] = { { 0xfc00, 0xfc0f, 16, "GPIO function sel" }, { 0xfc10, 0xfc1f, 16, "GPIO output enable" }, { 0xfc20, 0xfc2f, 16, "GPIO output" }, { 0xfc30, 0xfc3f, 16, "GPIO input" }, { 0xfc40, 0xfc4f, 16, "GPIO pull-up enable" }, { 0xfc50, 0xfc5f, 16, "GPIO open drain output enable" }, { 0xfc60, 0xfc6f, 16, "GPIO input enable" }, { 0xfc70, 0xfc7f, 16, "GPIO various" }, { 0xfc80, 0xfc8f, 16, "Keyboard Controller" }, { 0xfc90, 0xfc9f, 16, "ENE serial bus controller" }, { 0xfca0, 0xfcaf, 16, "Internal keyboard matrix" }, { 0xfcb0, 0xfcbf, 16, "for ESB?" }, { 0xfcc0, 0xfccf, 16, "for ESB?" }, { 0xfcd0, 0xfcdf, 16, "PECI controller" }, { 0xfce0, 0xfcef, 16, "Reserved" }, { 0xfcf0, 0xfcff, 16, "One Wire Master" }, { 0xfd00, 0xfdff, 256, "for ESB?" }, { 0xfe00, 0xfe1f, 32, "Pulse width modulation" }, { 0xfe20, 0xfe4f, 48, "Fan controller" }, { 0xfe50, 0xfe6f, 32, "General purpose timer" }, { 0xfe70, 0xfe7f, 16, "SPI host/device interface"}, { 0xfe80, 0xfe8f, 16, "Watchdog timer" }, { 0xfe90, 0xfe9f, 16, "Low pin count interface" }, { 0xfea0, 0xfebf, 32, "X-bus interface" }, { 0xfec0, 0xfecf, 16, "Consumer IR controller" }, { 0xfed0, 0xfedf, 16, "General Waveform Generation" }, { 0xfee0, 0xfeff, 32, "PS/2 interface" }, { 0xff00, 0xff2f, 48, "Embedded Controller" }, { 0xff30, 0xff7f, 80, "General purpose wakeup event" }, { 0xff80, 0xff8f, 16, "Reserved" }, { 0xff90, 0xffbf, 48, "SMBus controller 0" }, { 0xffc0, 0xffcf, 16, "Reserved" }, { 0xffd0, 0xffff, 48, "SMBus controller 1" } }; void Disassembly::autoComment() { int registerAreaCount = sizeof(registerAreas) / sizeof(*registerAreas); // check sizes for(int i1 = 0; i1 < registerAreaCount; i1++) { if(registerAreas[i1].addressFirst + registerAreas[i1].size - 1 != registerAreas[i1].addressLast) { logger->LogWarning(std::string("Invalid registerArea ") + registerAreas[i1].name); } } for(auto itInstruction = instructions.begin(); itInstruction != instructions.end(); itInstruction++) { if(itInstruction->second.getName() == "MOV DPTR, ") { for(int i1 = 0; i1 < registerAreaCount; i1++) { if(registerAreas[i1].contains(itInstruction->second.arg1)) { itInstruction->second.ac(std::string("Reg ") + registerAreas[i1].name); //std::cout << utils::Int_To_String_Hex(itInstruction->first) << " " << itInstruction->second.autocomment << std::endl; break; } } } if(itInstruction->second.isJump || itInstruction->second.isCondJump) { auto itFunction = findFunction(itInstruction->second.address); if(itFunction != functions.end()) { if(!itFunction->second.contains(itInstruction->first)) { // do not mark itself //if((itInstruction->first < itFunction->first) || (itInstruction->first >= itFunction->second.endAddress)) { if(itFunction->first == itInstruction->second.address) { itInstruction->second.ac("Fnc " + itFunction->second.name); } else { // mark it if it does not jump to the beginning of the function itInstruction->second.ac("FncPart " + itFunction->second.name); } } } auto itRemapCall = remapCalls.find(itInstruction->second.address); if(itRemapCall != remapCalls.end()) { if(itRemapCall->second.targetAddress >= 0) { auto itFunction = findFunction(itRemapCall->second.targetAddress); if(itFunction != functions.end()) { if(itFunction->first == itRemapCall->second.targetAddress) { itInstruction->second.ac("Rcl to Fnc " + itFunction->second.name); } else { itInstruction->second.ac("Rcl to FncPart " + itFunction->second.name); } } else { itInstruction->second.ac("Rcl to " + utils::Int_To_String_Hex(itRemapCall->second.targetAddress)); } } } } } for(const auto &pair : functions) { for(const Function::Block &block : pair.second.blocks) { auto itInstruction = instructions.find(block.begin); if(itInstruction->second.autocomment.empty()) { itInstruction->second.ac("Bgn " + pair.second.name); } itInstruction = instructions.find(block.end); if((itInstruction != instructions.end()) && (itInstruction != instructions.begin())) { itInstruction--; if(itInstruction->first + itInstruction->second.length == block.end) { if(itInstruction->second.autocomment.empty()) { itInstruction->second.ac("End " + pair.second.name); } } } } } for(const SwitchStatement &switchStatement : switchStatements) { std::vector<SwitchStatement::ValuesCase> valuesCases = switchStatement.groupCasesByValues(); for(SwitchStatement::ValuesCase valuesCase : valuesCases) { auto itInstruction = instructions.find(valuesCase.address); if(itInstruction == instructions.end()) { logger->LogError("Switch on " + utils::Int_To_String_Hex(switchStatement.address) + ": Should have an instruction for case block on address " + utils::Int_To_String_Hex(valuesCase.address)); continue; } itInstruction->second.ac("case " + valuesCase.formatValues() + " for switch on " + formatWithFunction(switchStatement.address)); } } } void Disassembly::resolveFunctionEndAddresses() { for(auto itFunction = functions.begin(); itFunction != functions.end(); itFunction++) { itFunction->second.blocks.clear(); } for(auto itFunction = functions.begin(); itFunction != functions.end(); itFunction++) { auto itNextFunction = itFunction; itNextFunction++; // if another function already has a block on the same address, delete or shrink the block, // because the user has expressed to start a new function on this address by adding this function auto itRivalFunction = findFunction(itFunction->first); if(itRivalFunction != functions.end()) { for(auto itBlock = itRivalFunction->second.blocks.begin(); itBlock != itRivalFunction->second.blocks.end(); itBlock++) { if(itBlock->contains(itFunction->first)) { //std::cout << "extra function " << itFunction->second.name << " " << itRivalFunction->second.name << " " << utils::Int_To_String_Hex(itFunction->first) << " " << utils::Int_To_String_Hex(itBlock->begin) << std::endl; if(itBlock->begin == itFunction->first) { // the block has no code before the beginning of the function itRivalFunction->second.blocks.erase(itBlock); } else { itBlock->end = itFunction->first; } break; } } } recurseFunction(itFunction, itNextFunction, itFunction->first); itFunction->second.defragmentBlocks(); } } void Disassembly::recurseFunction(std::map<uint64_t, Function>::iterator itFunction, std::map<uint64_t, Function>::iterator itNextFunction, uint64_t address) { auto itInstruction = instructions.find(address); if(itInstruction == instructions.end()) { // might be due to a previous "refusing to disassemble instruction" (on weird binaries) logger->LogError("Disassembly: Function " + itFunction->second.name + " should have been parsed before on address " + utils::Int_To_String_Hex(address)); return; } auto itNextFunctionInstruction = instructions.end(); if(itNextFunction != functions.end()) { itNextFunctionInstruction = instructions.find(itNextFunction->first); if(itNextFunctionInstruction == instructions.end()) { // might be due to a previous "refusing to disassemble instruction" (on weird binaries) logger->LogError("Disassembly: Next Function " + itNextFunction->second.name + " should have been parsed before on address " + utils::Int_To_String_Hex(itNextFunction->first)); return; } } Function::Block newBlock; newBlock.begin = address; newBlock.end = itInstruction->first + itInstruction->second.length; while(itInstruction != itNextFunctionInstruction) { auto itOtherFunction = findFunction(itInstruction->first); if(itOtherFunction == itFunction) { // this block was already added to the function // but we came maybe from a few bytes before, so find the block and add this to the block for(Function::Block &block : itOtherFunction->second.blocks) { if(block.contains(itInstruction->first)) { block.begin = std::min(block.begin, newBlock.begin); return; } } logger->LogError("Disassembly: Should have found block"); } else if(itOtherFunction != functions.end()) { logger->LogWarning("Disassembly: Function " + itFunction->second.name + " has some parts on address " + utils::Int_To_String_Hex(itInstruction->first) + ", but this block is also used by function " + itOtherFunction->second.name); newBlock.end = itInstruction->first; if(newBlock.end > newBlock.begin) { // do not store "empty" blocks itFunction->second.blocks.push_back(newBlock); } return; } if((itInstruction->second.getName() == "RET") || (itInstruction->second.getName() == "RETI") || (itInstruction->second.getName() == "JMP @A+DPTR")) { itFunction->second.blocks.push_back(newBlock); return; } if(itInstruction->second.isJump) { if(itInstruction->second.address != newBlock.end) { // sometimes, there are strange jumps to the next address itFunction->second.blocks.push_back(newBlock); recurseFunction(itFunction, functions.end(), itInstruction->second.address); return; } } if(itInstruction->second.isCondJump && (!itInstruction->second.isCall())) { itFunction->second.blocks.push_back(newBlock); // push the block temporarily, so that it is check by findFunction() to avoid endless recursion recurseFunction(itFunction, functions.end(), itInstruction->second.address); // now find the block we stored before and remove it from the blocks // we cannot rely on an index, because other recurseFunction calls might also use an index // we also cannot use a pointer, because std::vector sometimes changes the space allocated to a function // (but it would be ok if we would allocate the functions with new) for(auto itBlock = itFunction->second.blocks.begin(); itBlock != itFunction->second.blocks.end(); itBlock++) { if(itBlock->begin == newBlock.begin) { // we found our block itFunction->second.blocks.erase(itBlock); break; } } } itInstruction++; if(newBlock.end < itInstruction->first) { // some unparsed bytes in between break; } newBlock.end = itInstruction->first + itInstruction->second.length; } // we got to the next function or the end itFunction->second.blocks.push_back(newBlock); } void Disassembly::addFunction(int address, Function function) { functions[address] = function; if(instructions.find(address) == instructions.end()) { Disassembler disassembler(logger); disassembler.followCodePath(buf, address, this); // now we changed so much that it is easier to simply recalc the text box int oldCaretPos = textCtrl->GetCurrentPos(); textCtrl->ClearAll(); printToWx(textCtrl); textCtrl->GotoPos(oldCaretPos); } else { // TODO this only changes comments for direct calls to the function, but not those who call // a part of this function. auto itTarget = jumpTargets.find(address); if(itTarget != jumpTargets.end()) { for(uint64_t sourceAddress : itTarget->second) { instructions[sourceAddress].autocomment += "Fnc " + function.name; updateInstructionComment(sourceAddress, instructions[sourceAddress].comment); } } updateFunctionName(address, function.name); } resolveFunctionEndAddresses(); } void Disassembly::updateFunctionName(int address, std::string newName) { Function &function = functions[address]; // TODO this only changes comments for direct calls to the function, but not those who call // a part of this function. auto itTarget = jumpTargets.find(address); if(itTarget != jumpTargets.end()) { for(uint64_t sourceAddress : itTarget->second) { utils::str_replace_one(instructions[sourceAddress].autocomment, "Fnc " + function.name, "Fnc " + newName); updateInstructionComment(sourceAddress, instructions[sourceAddress].comment); } } function.name = newName; } void Disassembly::updateInstructionComment(int address, std::string newComment) { instructions[address].comment = newComment; updateLineAtAddress(address); } void Disassembly::updateLineAtAddress(int address) { int line = findLineByAddress(address); int startPos = textCtrl->PositionFromLine(line); int lineLength = textCtrl->LineLength(line) - 1; // -1 to not delete the \n textCtrl->DeleteRange(startPos, lineLength); TEXTCTRL_START_STYLING(textCtrl, startPos); InsertBufAddress(textCtrl, startPos, address); instructions[address].printToWx(textCtrl, startPos + 6); } void Disassembly::deleteFunction(int address) { Function functionCopy = functions[address]; functions.erase(address); resolveFunctionEndAddresses(); // TODO this only changes comments for direct calls to the function, but not those who call // a part of this function. auto itTarget = jumpTargets.find(address); if(itTarget != jumpTargets.end()) { for(uint64_t sourceAddress : itTarget->second) { utils::str_replace_one(instructions[sourceAddress].autocomment, "Fnc " + functionCopy.name, ""); updateInstructionComment(sourceAddress, instructions[sourceAddress].comment); } } } std::map<uint64_t, Function>::iterator Disassembly::findFunction(int addressIn) { for(auto itFunction = functions.begin(); itFunction != functions.end(); itFunction++) { if(itFunction->second.contains(addressIn)) { return itFunction; } } return functions.end(); /*auto itFunction = functions.begin(); while(addressIn >= itFunction->second.endAddress) { itFunction++; if(itFunction == functions.end()) { return functions.end(); } } if(addressIn >= itFunction->first) { return itFunction; } else { return functions.end(); }*/ } std::vector<uint64_t> Disassembly::GetFunctionTargetAddresses(uint64_t functionAddress) { std::vector<uint64_t> ret; const Function &function = functions[functionAddress]; for(const Function::Block &block : function.blocks) { auto itInstruction = instructions.find(block.begin); if(itInstruction == instructions.end()) { logger->LogError("Invalid block with address " + utils::Int_To_String_Hex(block.begin) + " of function " + function.name); continue; } while((itInstruction->first < block.end) && (itInstruction != instructions.end())) { if(itInstruction->second.isJump || itInstruction->second.isCondJump) { ret.push_back(itInstruction->second.address); } itInstruction++; } } return ret; } bool Disassembly::seemsToBeInvalidCode(uint64_t address) { if(address + 2 < buf.size()) { return (buf[address] == buf[address + 1]) && (buf[address] == buf[address + 2]); } return false; } std::string Disassembly::formatWithFunction(uint64_t address) { std::string str = utils::Int_To_String_Hex(address); auto itFunction = findFunction(address); if(itFunction != functions.end()) { str += " (" + itFunction->second.name + ")"; } return str; } int Disassembly::findSwitchStatementOnExact(uint64_t address) { for(std::size_t iSwitchStatement = 0; iSwitchStatement < switchStatements.size(); iSwitchStatement++) { if(switchStatements[iSwitchStatement].address == address) { return iSwitchStatement; } } return -1; } } // namespace disas8051
29,423
C++
.cpp
690
36.375362
222
0.653899
msrst/interactive-8051-disassembler
39
5
1
GPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,871
disassembler.cpp
msrst_interactive-8051-disassembler/8051/disassembler.cpp
/************************************************************************ * Copyright (C) 2020-2021 Matthias Rosenthal * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/> ***********************************************************************/ #include "disassembler.hpp" #include <stdio.h> #include <string.h> #include <iostream> #include "../utils/utils.hpp" namespace disas8051 { //all 256 op codes // table created by Collin Kidder Instruct8051 OpCodes[] = { // name len arg1 arg1 jmp cond-jmp {"NOP", 1, NONE, NONE, false, false}, {"AJMP ", 2, ADDR11, NONE, true, false}, {"LJMP ", 3, ADDR16, NONE, true, false}, {"RR A", 1, NONE, NONE, false, false}, {"INC A", 1, NONE, NONE, false, false}, {"INC ", 2, DIRECT, NONE, false, false}, {"INC @R0", 1, NONE, NONE, false, false}, {"INC @R1", 1, NONE, NONE, false, false}, {"INC R0", 1, NONE, NONE, false, false}, {"INC R1", 1, NONE, NONE, false, false}, {"INC R2", 1, NONE, NONE, false, false}, {"INC R3", 1, NONE, NONE, false, false}, {"INC R4", 1, NONE, NONE, false, false}, {"INC R5", 1, NONE, NONE, false, false}, {"INC R6", 1, NONE, NONE, false, false}, {"INC R7", 1, NONE, NONE, false, false}, //F {"JBC ", 3, BIT, OFFSET, false, true}, {"ACALL ", 2, ADDR11, NONE, false, true}, {"LCALL ", 3, ADDR16, NONE, false, true}, {"RRC A", 1, NONE, NONE, false, false}, {"DEC A", 1, NONE, NONE, false, false}, {"DEC ", 2, DIRECT, NONE, false, false}, {"DEC @R0", 1, NONE, NONE, false, false}, {"DEC @R1", 1, NONE, NONE, false, false}, {"DEC R0", 1, NONE, NONE, false, false}, {"DEC R1", 1, NONE, NONE, false, false}, {"DEC R2", 1, NONE, NONE, false, false}, {"DEC R3", 1, NONE, NONE, false, false}, {"DEC R4", 1, NONE, NONE, false, false}, {"DEC R5", 1, NONE, NONE, false, false}, {"DEC R6", 1, NONE, NONE, false, false}, {"DEC R7", 1, NONE, NONE, false, false}, //1F {"JB ", 3, BIT, OFFSET, false, true}, {"AJMP ", 2, ADDR11, NONE, true, false}, {"RET", 1, NONE, NONE, false, false}, {"RL A", 1, NONE, NONE, false, false}, {"ADD A, ", 2, IMMED, NONE, false, false}, {"ADD A, ", 2, DIRECT, NONE, false, false}, {"ADD A, @R0", 1, NONE, NONE, false, false}, {"ADD A, @R1", 1, NONE, NONE, false, false}, {"ADD A, R0", 1, NONE, NONE, false, false}, {"ADD A, R1", 1, NONE, NONE, false, false}, {"ADD A, R2", 1, NONE, NONE, false, false}, {"ADD A, R3", 1, NONE, NONE, false, false}, {"ADD A, R4", 1, NONE, NONE, false, false}, {"ADD A, R5", 1, NONE, NONE, false, false}, {"ADD A, R6", 1, NONE, NONE, false, false}, {"ADD A, R7", 1, NONE, NONE, false, false}, //2F {"JNB ", 3, BIT, OFFSET, false, true}, {"ACALL ", 2, ADDR11, NONE, false, true}, {"RETI", 1, NONE, NONE, false, false}, {"RLC A", 1, NONE, NONE, false, false}, {"ADDC A, ", 2, IMMED, NONE, false, false}, {"ADDC A, ", 2, DIRECT, NONE, false, false}, {"ADDC A, @R0", 1, NONE, NONE, false, false}, {"ADDC A, @R1", 1, NONE, NONE, false, false}, {"ADDC A, R0", 1, NONE, NONE, false, false}, {"ADDC A, R1", 1, NONE, NONE, false, false}, {"ADDC A, R2", 1, NONE, NONE, false, false}, {"ADDC A, R3", 1, NONE, NONE, false, false}, {"ADDC A, R4", 1, NONE, NONE, false, false}, {"ADDC A, R5", 1, NONE, NONE, false, false}, {"ADDC A, R6", 1, NONE, NONE, false, false}, {"ADDC A, R7", 1, NONE, NONE, false, false}, //3F {"JC ", 2, OFFSET, NONE, false, true}, {"AJMP ", 2, ADDR11, NONE, true, false}, {"ORL ", 2, DIRECT, A, false, false}, {"ORL ", 3, DIRECT, IMMED, false, false}, {"ORL A, ", 2, IMMED, NONE, false, false}, {"ORL A, ", 2, DIRECT, NONE, false, false}, {"ORL A, @R0", 1, NONE, NONE, false, false}, {"ORL A, @R1", 1, NONE, NONE, false, false}, {"ORL A, R0", 1, NONE, NONE, false, false}, {"ORL A, R1", 1, NONE, NONE, false, false}, {"ORL A, R2", 1, NONE, NONE, false, false}, {"ORL A, R3", 1, NONE, NONE, false, false}, {"ORL A, R4", 1, NONE, NONE, false, false}, {"ORL A, R5", 1, NONE, NONE, false, false}, {"ORL A, R6", 1, NONE, NONE, false, false}, {"ORL A, R7", 1, NONE, NONE, false, false}, //4F {"JNC ", 2, OFFSET, NONE, false, true}, {"ACALL ", 2, ADDR11, NONE, false, true}, {"ANL ", 2, DIRECT, A, false, false}, {"ANL ", 3, DIRECT, IMMED, false, false}, {"ANL A, ", 2, IMMED, NONE, false, false}, {"ANL A, ", 2, DIRECT, NONE, false, false}, {"ANL A, @R0", 1, NONE, NONE, false, false}, {"ANL A, @R1", 1, NONE, NONE, false, false}, {"ANL A, R0", 1, NONE, NONE, false, false}, {"ANL A, R1", 1, NONE, NONE, false, false}, {"ANL A, R2", 1, NONE, NONE, false, false}, {"ANL A, R3", 1, NONE, NONE, false, false}, {"ANL A, R4", 1, NONE, NONE, false, false}, {"ANL A, R5", 1, NONE, NONE, false, false}, {"ANL A, R6", 1, NONE, NONE, false, false}, {"ANL A, R7", 1, NONE, NONE, false, false}, //5F {"JZ ", 2, OFFSET, NONE, false, true}, {"AJMP ", 2, ADDR11, NONE, true, false}, {"XRL ", 2, DIRECT, A, false, false}, {"XRL ", 3, DIRECT, IMMED, false, false}, {"XRL A, ", 2, IMMED, NONE, false, false}, {"XRL A, ", 2, DIRECT, NONE, false, false}, {"XRL A, @R0", 1, NONE, NONE, false, false}, {"XRL A, @R1", 1, NONE, NONE, false, false}, {"XRL A, R0", 1, NONE, NONE, false, false}, {"XRL A, R1", 1, NONE, NONE, false, false}, {"XRL A, R2", 1, NONE, NONE, false, false}, {"XRL A, R3", 1, NONE, NONE, false, false}, {"XRL A, R4", 1, NONE, NONE, false, false}, {"XRL A, R5", 1, NONE, NONE, false, false}, {"XRL A, R6", 1, NONE, NONE, false, false}, {"XRL A, R7", 1, NONE, NONE, false, false}, //6F {"JNZ ", 2, OFFSET, NONE, false, true}, {"ACALL ", 2, ADDR11, NONE, false, true}, {"ORL C, ", 2, BIT, NONE, false, false}, {"JMP @A+DPTR", 1, NONE, NONE, false, false}, //yes, this really is a jump instr. but this program can't decode DPTR so don't follow it. {"MOV A, ", 2, IMMED, NONE, false, false}, {"MOV ", 3, DIRECT, IMMED, false, false}, {"MOV @R0, ", 2, IMMED, NONE, false, false}, {"MOV @R1, ", 2, IMMED, NONE, false, false}, {"MOV R0, ", 2, IMMED, NONE, false, false}, {"MOV R1, ", 2, IMMED, NONE, false, false}, {"MOV R2, ", 2, IMMED, NONE, false, false}, {"MOV R3, ", 2, IMMED, NONE, false, false}, {"MOV R4, ", 2, IMMED, NONE, false, false}, {"MOV R5, ", 2, IMMED, NONE, false, false}, {"MOV R6, ", 2, IMMED, NONE, false, false}, {"MOV R7, ", 2, IMMED, NONE, false, false}, //7F {"SJMP ", 2, OFFSET, NONE, true, false}, {"AJMP ", 2, ADDR11, NONE, true, false}, {"ANL C, ", 2, BIT, NONE, false, false}, {"MOVC A, @A+PC", 1, NONE, NONE, false, false}, {"DIV AB", 1, NONE, NONE, false, false}, {"MOV ", 3, DIRECT, DIRECT, false, false}, //85 {"MOV ", 2, DIRECT, IR0, false, false}, {"MOV ", 2, DIRECT, IR1, false, false}, {"MOV ", 2, DIRECT, R0, false, false}, {"MOV ", 2, DIRECT, R1, false, false}, {"MOV ", 2, DIRECT, R2, false, false}, {"MOV ", 2, DIRECT, R3, false, false}, {"MOV ", 2, DIRECT, R4, false, false}, {"MOV ", 2, DIRECT, R5, false, false}, {"MOV ", 2, DIRECT, R6, false, false}, {"MOV ", 2, DIRECT, R7, false, false}, //8F {"MOV DPTR, ", 3, IMMED16, NONE, false, false}, {"ACALL ", 2, ADDR11, NONE, false, true}, {"MOV ", 2, BIT, C, false, false}, {"MOVC A, @A+DPTR", 1, NONE, NONE, false, false}, {"SUBB A, ", 2, IMMED, NONE, false, false}, {"SUBB A, ", 2, DIRECT, NONE, false, false}, {"SUBB A, @R0", 1, NONE, NONE, false, false}, {"SUBB A, @R1", 1, NONE, NONE, false, false}, {"SUBB A, R0", 1, NONE, NONE, false, false}, {"SUBB A, R1", 1, NONE, NONE, false, false}, {"SUBB A, R2", 1, NONE, NONE, false, false}, {"SUBB A, R3", 1, NONE, NONE, false, false}, {"SUBB A, R4", 1, NONE, NONE, false, false}, {"SUBB A, R5", 1, NONE, NONE, false, false}, {"SUBB A, R6", 1, NONE, NONE, false, false}, {"SUBB A, R7", 1, NONE, NONE, false, false}, //9F {"ORL C, ", 2, BIT, NONE, false, false}, {"AJMP ", 2, ADDR11, NONE, true, false}, {"MOV C, ", 2, BIT, NONE, false, false}, {"INC DPTR", 1, NONE, NONE, false, false}, {"MUL AB", 1, NONE, NONE, false, false}, {"RESERVED", 1, NONE, NONE, false, false}, {"MOV @R0, ", 2, DIRECT, NONE, false, false}, {"MOV @R1, ", 2, DIRECT, NONE, false, false}, {"MOV R0, ", 2, DIRECT, NONE, false, false}, {"MOV R1, ", 2, DIRECT, NONE, false, false}, {"MOV R2, ", 2, DIRECT, NONE, false, false}, {"MOV R3, ", 2, DIRECT, NONE, false, false}, {"MOV R4, ", 2, DIRECT, NONE, false, false}, {"MOV R5, ", 2, DIRECT, NONE, false, false}, {"MOV R6, ", 2, DIRECT, NONE, false, false}, {"MOV R7, ", 2, DIRECT, NONE, false, false}, //AF {"ANL C, ", 2, BIT, NONE, false, false}, {"ACALL ", 2, ADDR11, NONE, false, true}, {"CPL ", 2, BIT, NONE, false, false}, {"CPL C", 1, NONE, NONE, false, false}, {"CJNE A, ", 3, IMMED, OFFSET, false, true}, {"CJNE A, ", 3, DIRECT, OFFSET, false, true}, {"CJNE @R0, ", 3, IMMED, OFFSET, false, true}, {"CJNE @R1, ", 3, IMMED, OFFSET, false, true}, {"CJNE R0, ", 3, IMMED, OFFSET, false, true}, {"CJNE R1, ", 3, IMMED, OFFSET, false, true}, {"CJNE R2, ", 3, IMMED, OFFSET, false, true}, {"CJNE R3, ", 3, IMMED, OFFSET, false, true}, {"CJNE R4, ", 3, IMMED, OFFSET, false, true}, {"CJNE R5, ", 3, IMMED, OFFSET, false, true}, {"CJNE R6, ", 3, IMMED, OFFSET, false, true}, {"CJNE R7, ", 3, IMMED, OFFSET, false, true}, //BF {"PUSH ", 2, DIRECT, NONE, false, false}, {"AJMP ", 2, ADDR11, NONE, true, false}, {"CLR ", 2, BIT, NONE, false, false}, {"CLR C", 1, NONE, NONE, false, false}, {"SWAP A", 1, NONE, NONE, false, false}, {"XCH A, ", 2, DIRECT, NONE, false, false}, {"XCH A, @R0", 1, NONE, NONE, false, false}, {"XCH A, @R1", 1, NONE, NONE, false, false}, {"XCH A, R0", 1, NONE, NONE, false, false}, {"XCH A, R1", 1, NONE, NONE, false, false}, {"XCH A, R2", 1, NONE, NONE, false, false}, {"XCH A, R3", 1, NONE, NONE, false, false}, {"XCH A, R4", 1, NONE, NONE, false, false}, {"XCH A, R5", 1, NONE, NONE, false, false}, {"XCH A, R6", 1, NONE, NONE, false, false}, {"XCH A, R7", 1, NONE, NONE, false, false}, //CF {"POP ", 2, DIRECT, NONE, false, false}, {"ACALL ", 2, ADDR11, NONE, false, true}, {"SETB ", 2, BIT, NONE, false, false}, {"SETB C", 1, NONE, NONE, false, false}, {"DA A", 1, NONE, NONE, false, false}, {"DJNZ ", 3, DIRECT, OFFSET, false, true}, {"XCHD A, @R0", 1, NONE, NONE, false, false}, {"XCHD A, @R1", 1, NONE, NONE, false, false}, {"DJNZ R0, ", 2, OFFSET, NONE, false, true}, {"DJNZ R1, ", 2, OFFSET, NONE, false, true}, {"DJNZ R2, ", 2, OFFSET, NONE, false, true}, {"DJNZ R3, ", 2, OFFSET, NONE, false, true}, {"DJNZ R4, ", 2, OFFSET, NONE, false, true}, {"DJNZ R5, ", 2, OFFSET, NONE, false, true}, {"DJNZ R6, ", 2, OFFSET, NONE, false, true}, {"DJNZ R7, ", 2, OFFSET, NONE, false, true}, //DF {"MOVX A, @DPTR", 1, NONE, NONE, false, false}, {"AJMP ", 2, ADDR11, NONE, true, false}, {"MOVX, A, @R0", 1, NONE, NONE, false, false}, {"MOVX, A, @R1", 1, NONE, NONE, false, false}, {"CLR A", 1, NONE, NONE, false, false}, {"MOV A, ", 2, DIRECT, NONE, false, false}, {"MOV A, @R0", 1, NONE, NONE, false, false}, {"MOV A, @R1", 1, NONE, NONE, false, false}, {"MOV A, R0", 1, NONE, NONE, false, false}, {"MOV A, R1", 1, NONE, NONE, false, false}, {"MOV A, R2", 1, NONE, NONE, false, false}, {"MOV A, R3", 1, NONE, NONE, false, false}, {"MOV A, R4", 1, NONE, NONE, false, false}, {"MOV A, R5", 1, NONE, NONE, false, false}, {"MOV A, R6", 1, NONE, NONE, false, false}, {"MOV A, R7", 1, NONE, NONE, false, false}, //EF {"MOVX @DPTR, A", 1, NONE, NONE, false, false}, {"ACALL ", 2, ADDR11, NONE, false, true}, {"MOVX @R0, A", 1, NONE, NONE, false, false}, {"MOVX @R1, A", 1, NONE, NONE, false, false}, {"CPL A", 1, NONE, NONE, false, false}, {"MOV ", 2, DIRECT, A, false, false}, {"MOV @R0, A", 1, NONE, NONE, false, false}, {"MOV @R1, A", 1, NONE, NONE, false, false}, {"MOV R0, A", 1, NONE, NONE, false, false}, {"MOV R1, A", 1, NONE, NONE, false, false}, {"MOV R2, A", 1, NONE, NONE, false, false}, {"MOV R3, A", 1, NONE, NONE, false, false}, {"MOV R4, A", 1, NONE, NONE, false, false}, {"MOV R5, A", 1, NONE, NONE, false, false}, {"MOV R6, A", 1, NONE, NONE, false, false}, {"MOV R7, A", 1, NONE, NONE, false, false} //FF }; //Starting at 0x80 and going through 0xFF these are the SFR's for a ENE KB9012 const char *SFR[] = { "P0IE", "SP", "DPL", "DPH", "x84", "x85", "PCON2","PCON", //80-87 "TCON", "TMOD", "TL0", "TL1", "TH0", "TH1", "x8e", "x8f", //88-8F "P1IE", "x91", "x92", "x93", "x94", "x95", "x96", "x97", //90-87 "SCON", "SBUF", "SCON2","SCON3","SCON4","x9d", "x9e", "x9f", //98-8F "P2", "xa1", "xa2", "xa3", "xa4", "xa5", "xa6", "xa7", //a0-a7 "IE", "xa9", "xaa", "xab", "xac", "xad", "xae", "xaf", //a8-af "P3IE", "xb1", "xb2", "xb3", "xb4", "xb5", "xb6", "xb7", //b0-b7 "IP", "xb9", "xba", "xbb", "xbc", "xbd", "xbe", "xbf", //b8-bf "xc0", "xc1", "xc2", "xc3", "xc4", "xc5", "xc6", "xc7", //c0-c7 "xc8", "xc9", "xca", "xcb", "xcc", "xcd", "xce", "xcf", //c8-cf "PSW", "xd1", "xd2", "xd3", "xd4", "xd5", "xd6", "xd7", //d0-d7 "P0IF", "xd9", "xda", "xdb", "xdc", "xdd", "xde", "xdf", //d8-df "ACC", "xe1", "xe2", "xe3", "xe4", "xe5", "xe6", "xe7", //e0-e7 "P1IF", "xe9", "xea", "xeb", "xec", "xed", "xee", "xef", //e8-ef "B", "xf1", "xf2", "xf3", "xf4", "xf5", "xf6", "xf7", //f0-f7 "P3IF", "xf9", "xfa", "xfb", "xfc", "xfd", "xfe", "xff" //f8-ff }; Disassembler::Disassembler(logger::logger_base *logger) { this->logger = logger; // SFR name check for(int i = 0; i < 128; i++) { if(SFR[i][0] == 'x') { std::string correctHex = fn_FormatToHex(ustring(1, (uint8_t)(i+128)), true); if(correctHex != SFR[i] + 1) { logger->LogWarning(std::string("SFR for ") + correctHex + std::string(" does not match its name ") + SFR[i]); } } } } int32_t Disassembler::resolveAddress(int32_t rawAddress, uint32_t currentAddress) { if(currentAddress >= 0x1C000) { if(rawAddress < 0x4000) { return rawAddress + 0x1C000; } } else if(currentAddress >= 0x18000) { if(rawAddress < 0x4000) { return rawAddress + 0x18000; } // else: e. g. library call on function in regular area } else if(currentAddress >= 0x14000) { if(rawAddress < 0x4000) { return rawAddress + 0x14000; } // else: e. g. library call on function in regular area } else if(currentAddress >= 0x10000) { if(rawAddress < 0x4000) { return rawAddress + 0x10000; } // else: e. g. library call on function in regular area } return rawAddress; } int Disassembler::interpretArgument(int32_t *outInt, const uint8_t *inBuffer, int opType, uint32_t address, int op) { int32_t tempInt = 0; int offset = 0; int opSize = OpCodes[op].length; switch(opType) { case NONE: offset = 0; tempInt = 0; break; case ADDR11: //take top 5 bits of PC (of following instruction), fill in bottom with these 11 bits. tempInt = (((uint16_t)(op & 0xE0)) << 3) + inBuffer[0] + ((address + opSize) & 0x0FF800); offset = 1; break; case ADDR16: //direct 16 bit address with no offsets tempInt = resolveAddress(((uint16_t)inBuffer[0] << 8) + inBuffer[1], address); offset = 2; break; case DIRECT: //direct 8 bit RAM or SFR tempInt = inBuffer[0]; offset = 1; break; case IMMED: //an 8 bit literal tempInt = inBuffer[0]; offset = 1; break; case IMMED16: //a 16 bit literal tempInt = ((uint16_t)inBuffer[0] << 8) + inBuffer[1]; offset = 2; break; case BIT: //a bit from one of the bitfield locations tempInt = inBuffer[0]; offset = 1; break; case OFFSET: //an offset from the end of this current instruction tempInt = address + opSize + (signed char)(inBuffer[0]); offset = 1; break; default: tempInt = 0; offset = 0; } *outInt = tempInt; return offset; } Instruction Disassembler::disassembleInstruction(const ustring &buf, uint64_t address) { int offset = 0; Instruction op; op.opNum = buf[address]; op.length = OpCodes[op.opNum].length; op.arg1Type = OpCodes[op.opNum].arg1; op.arg2Type = OpCodes[op.opNum].arg2; op.isJump = OpCodes[op.opNum].isJump; op.isCondJump = OpCodes[op.opNum].isCondJump; if(address + op.length > buf.length()) { logger->LogWarning("disassembled nothing on address " + utils::Int_To_String_Hex(address) + " because no more data"); op.opNum = NONE; return op; } offset = interpretArgument(&op.arg1, buf.data() + address + 1, op.arg1Type, address, op.opNum); offset = interpretArgument(&op.arg2, buf.data() + address + 1 + offset, op.arg2Type, address, op.opNum); if (op.arg1Type == ADDR11 || op.arg1Type == ADDR16 || op.arg1Type == OFFSET) { op.address = op.arg1; } if (op.arg2Type == ADDR11 || op.arg2Type == ADDR16 || op.arg2Type == OFFSET) { op.address = op.arg2; } return op; } void Disassembler::disassembleSwitchStatement(const ustring &buf, uint64_t callAddress, uint64_t startAddress, bool isI16Switch, Disassembly *disassembly) { SwitchStatement switchStatement; switchStatement.address = callAddress; switchStatement.isI16 = isI16Switch; logger->LogInformation("Disassembling switch on address " + utils::Int_To_String_Hex(callAddress)); uint64_t caseWidth = isI16Switch ? 4 : 3; while(startAddress + caseWidth <= buf.length()) { if((buf[startAddress] == 0) && (buf[startAddress+1] == 0)) { // default case uint64_t address = resolveAddress(((uint16_t)buf[startAddress+2] << 8) + buf[startAddress+3], startAddress); //std::cout << "default goto " << utils::Int_To_String_Hex(address) << std::endl; switchStatement.cases.push_back(SwitchStatement::Case{SwitchStatement::DEFAULT_CASE_VALUE, address}); followCodePath(buf, address, disassembly); break; } else { uint64_t address = resolveAddress(((uint16_t)buf[startAddress] << 8) + buf[startAddress+1], startAddress); int32_t value; if(isI16Switch) { value = ((uint16_t)buf[startAddress+2] << 8) + buf[startAddress+3]; } else { value = buf[startAddress+2]; } //std::cout << "case " << value << " goto " << utils::Int_To_String_Hex(address) << std::endl; switchStatement.cases.push_back(SwitchStatement::Case{value, address}); followCodePath(buf, address, disassembly); } startAddress += caseWidth; } int index = disassembly->switchStatements.size(); for(const SwitchStatement::Case &caseBlock : switchStatement.cases) { if(disassembly->caseBlocks.find(caseBlock.address) != disassembly->caseBlocks.end()) { if(disassembly->caseBlocks[caseBlock.address] == index) { continue; // This is a case block for multiple case values } logger->LogWarning("Case block for multiple switch statements on address " + utils::Int_To_String_Hex(caseBlock.address)); } disassembly->caseBlocks[caseBlock.address] = index; } disassembly->switchStatements.push_back(switchStatement); } void Disassembler::followCodePath(const ustring &buf, uint64_t startAddress, Disassembly *disassembly) { Instruction currentOp; #ifdef DEBUG printf("Start of code path: %x\n", startAddress); #endif while (true) { if(startAddress > buf.length()) { logger->LogWarning("Got to invalid address " + utils::Int_To_String_Hex(startAddress) + " outside data"); return; } if(disassembly->ignoreBlocks.find(startAddress) != disassembly->ignoreBlocks.end()) { std::cout << "ignoring from " << utils::Int_To_String_Hex(startAddress) << " on " << std::endl; return; } auto itOtherInstruction = disassembly->instructions.find(startAddress); if(itOtherInstruction != disassembly->instructions.end()) { // do not parse this block again return; } //decode the next instruction currentOp = disassembleInstruction(buf, startAddress); // I first tried auto itOp = instructions.begin(); while(itOp->first<startAddress) itOp++; // but this was suprisingly much slower than the following (see comment at file bottom for old code) for(int iByte = 0; iByte < currentOp.length; iByte++) { if(disassembly->instructions.find(startAddress + iByte) != disassembly->instructions.end()) { logger->LogWarning("Refusing to disassemble instruction on " + utils::Int_To_String_Hex(startAddress) + " because it overlaps with instruction on " + utils::Int_To_String_Hex(startAddress + iByte)); return; } } disassembly->instructions[startAddress] = currentOp; //if this instruction could possibly jump then take that jump if (currentOp.isCondJump || currentOp.isJump) { auto it = disassembly->jumpTargets.find(currentOp.address); if(it == disassembly->jumpTargets.end()) { disassembly->jumpTargets[currentOp.address] = std::vector<uint64_t>{startAddress}; } else { it->second.push_back(startAddress); } followCodePath(buf, currentOp.address, disassembly); auto itFunction = disassembly->functions.find(currentOp.address); if(itFunction != disassembly->functions.end()) { if(itFunction->second.name.find("CCASE") != std::string::npos) { disassembleSwitchStatement(buf, startAddress, startAddress + currentOp.length, false, disassembly); break; // the CCASE/ICASE function drops the return address and jumps to the case // statement -> the code does not necesarrily continue after the switch statement } else if(itFunction->second.name.find("ICASE") != std::string::npos) { disassembleSwitchStatement(buf, startAddress, startAddress + currentOp.length, true, disassembly); break; } } } //there are a variety of reasons we might quit going forward here. //perhaps this is a non-conditional jump. In that case we can't go anymore //or, perhaps we hit a RET or RETI instruction. So, check for all of the above if (currentOp.isJump || (currentOp.getName() == "RET") || (currentOp.getName() == "RETI") || (currentOp.getName() == "JMP @A+DPTR")) { #ifdef DEBUG printf("End of code path at: %x\n", startAddress); #endif return; } startAddress += currentOp.length; } } } // namespace disas8051 /* old code to check for overlapping // this is somehow much slower than disassembly->instructions.find(startAddress). auto itOtherInstruction = disassembly->instructions.begin(); while((itOtherInstruction != disassembly->instructions.end()) && (itOtherInstruction->first < startAddress)) { itOtherInstruction++; } if(itOtherInstruction != disassembly->instructions.end()) { if(itOtherInstruction->first == startAddress) { // do not parse this block again return; } } //decode the next instruction currentOp = disassembleInstruction(buf, startAddress); if(itOtherInstruction != disassembly->instructions.end()) { if(itOtherInstruction->first < startAddress + currentOp.length) { logger->LogWarning("Refusing to disassemble instruction on " + utils::Int_To_String_Hex(startAddress) + " because it overlaps with instruction on " + utils::Int_To_String_Hex(itOtherInstruction->first)); return; } } disassembly->instructions[startAddress] = currentOp; */
24,741
C++
.cpp
549
40.083789
154
0.589831
msrst/interactive-8051-disassembler
39
5
1
GPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,872
instruction.cpp
msrst_interactive-8051-disassembler/8051/instruction.cpp
/************************************************************************ * Copyright (C) 2020-2021 Matthias Rosenthal * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/> ***********************************************************************/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <iostream> #include "wx/stc/stc.h" #include "instruction.hpp" #include "disassembler.hpp" namespace disas8051 { std::string printArgument(int argType, int32_t value) { char *outBuffer = new char[10]; outBuffer[0] = '\0'; switch(argType) { case NONE: break; case ADDR11: sprintf(outBuffer, "0x%04X", value); break; case ADDR16: sprintf(outBuffer, "0x%04X", value); break; case DIRECT: if (value < 0x80) sprintf(outBuffer, "X%02Xh", value); else strcpy(outBuffer, SFR[value - 0x80]); break; case IMMED: sprintf(outBuffer, "#0x%02X", value); break; case IMMED16: sprintf(outBuffer, "#0x%04X", value); break; case BIT: //the last 128 bits are in 80, 88, 90, 98 that is 0x80 and upward 8 at a time if (value < 0x80) //bits from bytes 0x20 to 0x2F { sprintf(outBuffer, "X%X.%d", 0x20 + (value / 8), value % 8); } else { sprintf(outBuffer, "%s.%d", SFR[((value & 0xF8)-0x80)], value & 0x07); } break; case OFFSET: sprintf(outBuffer, "0x%04X", value); break; case A: sprintf(outBuffer, "A"); break; case C: sprintf(outBuffer, "C"); break; case IR0: sprintf(outBuffer, "@R0"); break; case IR1: sprintf(outBuffer, "@R1"); break; case R0: sprintf(outBuffer, "R0"); break; case R1: sprintf(outBuffer, "R1"); break; case R2: sprintf(outBuffer, "R2"); break; case R3: sprintf(outBuffer, "R3"); break; case R4: sprintf(outBuffer, "R4"); break; case R5: sprintf(outBuffer, "R5"); break; case R6: sprintf(outBuffer, "R6"); break; case R7: sprintf(outBuffer, "R7"); break; } std::string str(outBuffer); delete[] outBuffer; return str; } std::string Instruction::getName() { return OpCodes[opNum].name; } bool Instruction::isCall() { return (getName() == "LCALL ") || (getName() == "ACALL "); } std::string Instruction::formatSimple() { std::string arg1Str; std::string arg2Str; if (opNum != 0x85) { arg1Str = printArgument(arg1Type, arg1); arg2Str = printArgument(arg2Type, arg2); } else //some joker decided that this instruction and this instruction only should have reversed operands. Why?! I guess it was really funny. { arg2Str = printArgument(arg1Type, arg1); arg1Str = printArgument(arg2Type, arg2); } if (arg2Str.empty()) { if(arg1Str.empty()) { return getName(); } else { return getName() + ' ' + arg1Str; } } else { return getName() + ' ' + arg1Str + ", " + arg2Str; } } void Instruction::ac(std::string c) { if(autocomment.empty()) { autocomment = c; } else { autocomment += ", "; autocomment += c; } } std::string Instruction::getFullComment() { if(autocomment.empty()) { return comment; } else if(comment.empty()) { return autocomment; } else { return autocomment + ", " + comment; } } void Instruction::printToWx(wxStyledTextCtrl *textCtrl) { std::string fs = formatSimple(); textCtrl->AppendText(wxString::FromUTF8(fs.c_str())); if((fs == "RET") || (fs == "RETI")) { textCtrl->SetStyling(fs.length(), (int)Styles::RET_INSTRUCTION); } else { textCtrl->SetStyling(fs.length(), (int)Styles::DEFAULT); } std::string fullComment = getFullComment(); if(!fullComment.empty()) { fullComment = std::string(24 - fs.size(), ' ') + "; " + fullComment; textCtrl->AppendText(wxString::FromUTF8(fullComment.c_str())); textCtrl->SetStyling(fullComment.length(), (int)Styles::COMMENT); } } void Instruction::printToWx(wxStyledTextCtrl *textCtrl, int pos) { std::string fs = formatSimple(); textCtrl->InsertText(pos, wxString::FromUTF8(fs.c_str())); if((fs == "RET") || (fs == "RETI")) { textCtrl->SetStyling(fs.length(), (int)Styles::RET_INSTRUCTION); } else { textCtrl->SetStyling(fs.length(), (int)Styles::DEFAULT); } std::string fullComment = getFullComment(); if(!fullComment.empty()) { fullComment = std::string(24 - fs.size(), ' ') + "; " + fullComment; textCtrl->InsertText(pos + fs.length(), wxString::FromUTF8(fullComment.c_str())); textCtrl->SetStyling(fullComment.length(), (int)Styles::COMMENT); } } } // namespace disas8051
5,595
C++
.cpp
193
23.212435
144
0.589658
msrst/interactive-8051-disassembler
39
5
1
GPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,873
function.cpp
msrst_interactive-8051-disassembler/8051/function.cpp
/************************************************************************ * Copyright (C) 2020-2021 Matthias Rosenthal * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/> ***********************************************************************/ #include "function.hpp" #include "../utils/utils.hpp" namespace disas8051 { bool Function::contains(uint64_t address) { for(const Block &block : blocks) { if(block.contains(address)) { return true; } } return false; } std::string Function::getBlockSummary() { std::string ret = utils::Int_To_String_Hex(blocks[0].begin) + ".." + utils::Int_To_String_Hex(blocks[0].end); for(std::size_t i1 = 1; i1 < blocks.size(); i1++) { ret += ", " + utils::Int_To_String_Hex(blocks[i1].begin) + ".." + utils::Int_To_String_Hex(blocks[i1].end); } return ret; } void Function::defragmentBlocks() { bool fragmented; do { fragmented = false; for(std::size_t iBlock = 0; iBlock < blocks.size(); iBlock++) { for(std::size_t iBlockCompare = iBlock; iBlockCompare < blocks.size(); iBlockCompare++) { if(blocks[iBlock].end == blocks[iBlockCompare].begin) { blocks[iBlock].end = blocks[iBlockCompare].end; blocks.erase(blocks.begin() + iBlockCompare); fragmented = true; } else if(blocks[iBlock].begin == blocks[iBlockCompare].end) { blocks[iBlock].begin = blocks[iBlockCompare].begin; blocks.erase(blocks.begin() + iBlockCompare); fragmented = true; } } } } while(fragmented); } } // namespace disas8051
2,129
C++
.cpp
57
33.526316
111
0.639145
msrst/interactive-8051-disassembler
39
5
1
GPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,874
consts.hpp
msrst_interactive-8051-disassembler/consts.hpp
/************************************************************************ * Copyright (C) 2020-2021 Matthias Rosenthal * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/> ***********************************************************************/ #ifndef CONSTS_HPP_INCLUDED #define CONSTS_HPP_INCLUDED #define LOGGER_MAX_LOGS (100000) #define TIMER_GUI_UPDATE_INTERVAL_MS (50) #define LOGGER_WXTEXTCTRL #endif // CONSTS_HPP_INCLUDED
1,020
C++
.h
21
45.380952
74
0.647773
msrst/interactive-8051-disassembler
39
5
1
GPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,875
wxMain.h
msrst_interactive-8051-disassembler/wxMain.h
/************************************************************************ * Copyright (C) 2020-2021 Matthias Rosenthal * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/> ***********************************************************************/ #ifndef DISAS8051_MAIN_H_INCLUDED #define DISAS8051_MAIN_H_INCLUDED #include <wx/wx.h> #include "wx/spinctrl.h" #include "wx/imaglist.h" #include "wx/artprov.h" #include "wx/notebook.h" #include "wx/dataview.h" #include "wx/hashmap.h" #include "wx/richtext/richtextctrl.h" #include "wx/stc/stc.h" #include "wx/splitter.h" #include "wx/scrolwin.h" #include "wx/checkbox.h" #include "wxApp.h" #include "utils/logger.h" #include "gui/gui_palette.h" #include "8051/disassembler.hpp" #include "scroll_overview.hpp" #include "function_graph.hpp" #include "annotation_canvas.hpp" class Dis8051Frame: public wxFrame { private: boost::shared_ptr<logger::logger> c_logger; wxTimer timer_gui_update1; Dis8051App *m_app; gui_palette c_gui_palette; ScrollOverview *scroll_overview; wxSplitterWindow *wxsw_main; AnnotationCanvas *annotation_canvas; wxStyledTextCtrl *wxrt_disassembly; wxTextCtrl *wxtc_referalls; wxCheckBox *wxc_search_hex; wxTextCtrl *wxtc_search; wxTextCtrl *wxtc_comment; wxTextCtrl *wxtc_function; wxCheckBox *wxc_function_shown; wxTextCtrl *wxtc_function_blocks; FunctionGraph *function_graph; wxTextCtrl *wxtc_log; std::string firmwareFile; std::string metaFile; std::shared_ptr<disas8051::Disassembly> disassembly; public: Dis8051Frame(wxFrame *frame, const wxString& title, std::string firmwareFile, std::string metaFile, Dis8051App *app); ~Dis8051Frame(); disas8051::Disassembly *getDisassembly() { return disassembly.get(); } void GetDisassemblyLinesOnScreen(int *lineBegin, int *lineEnd); void OnOverviewLineClicked(int line); void OnFunctionClicked(uint64_t address, disas8051::Function *function); private: enum { idMenuQuit = 1000, idMenuAbout, idMenuFindNext, idMenuFindPrevious, idMenuGoto, idMenuSaveMetaFile, idMenuToggleCallAnnotation, idMenuReadAddressFromCode, idTimerUpdateUI, idDisassemblyTextCtrl, idTextCtrlSearch, idButtonFindBefore, idButtonFindNext, idTextCtrlComment, idTextCtrlFunction, idCheckBoxFunctionShown, idButtonDeleteFunction }; void OnClose(wxCloseEvent &event); void OnQuit(wxCommandEvent &event); void OnAbout(wxCommandEvent &event); void OnSaveMetaFile(wxCommandEvent &event); void OnTimerUpdateUI(wxTimerEvent &event); void OnDisassemblyTextUpdated(wxStyledTextEvent &event); void OnDissassemblyCaretMove(); void OnFindBefore(wxCommandEvent &event); void OnFindNext(wxCommandEvent &event); void OnGoto(wxCommandEvent &event); void OnCommentEnterPressed(wxCommandEvent &event); void OnFunctionEnterPressed(wxCommandEvent &event); void OnToggleFunctionShown(wxCommandEvent &event); void OnFunctionDelete(wxCommandEvent &event); void OnToggleCallAnnotation(wxCommandEvent &event); void OnReadAddressFromCode(wxCommandEvent &event); void messageGUI(std::string msg); void doSearch(bool previous); std::string getAddressDescription(uint64_t address); int queryAddressFromUser(wxString title, int defaultAddres = -1); // return -1 if invalid address, address if correct (also checks bounds). DECLARE_EVENT_TABLE() }; std::basic_string<uint8_t> Uint16t_To_UString(uint16_t var); #endif // DISAS8051_MAIN_H_INCLUDED
4,355
C++
.h
113
33
144
0.70388
msrst/interactive-8051-disassembler
39
5
1
GPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,876
function_graph.hpp
msrst_interactive-8051-disassembler/function_graph.hpp
/************************************************************************ * Copyright (C) 2020-2021 Matthias Rosenthal * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/> ***********************************************************************/ #ifndef FUNCTION_GRAPH_HPP_INCLUDED #define FUNCTION_GRAPH_HPP_INCLUDED #include <vector> #include <unordered_map> #include <map> #include "wx/scrolwin.h" #include "8051/function.hpp" #include "8051/remap_call.hpp" class Dis8051Frame; class FunctionGraph : public wxScrolledCanvas { private: const int MARGIN = 2; Dis8051Frame *mainFrame; int w,h; struct CachedFunction { uint64_t address; disas8051::Function *function; std::map<std::size_t, bool> targetIndexes; // true if direct call, false if only a part called std::vector<std::size_t> remapCallIndexes; int rectWidth; int rectHeight; }; std::vector<CachedFunction> cachedFunctions; struct CachedRemapCall { uint64_t address; disas8051::RemapCall *remapCall; int targetIndex; // -1 if the target function is not named by user bool isDirectCall; // false if only a part of the targetIndex-function called // currently unused! (it is not drawn) int rectWidth; int rectHeight; }; std::vector<CachedRemapCall> cachedRemapCalls; wxFont font; bool isDragging = false; int dragStartX; int dragStartY; int dragCurrentX; int dragCurrentY; bool isDraggingFunction = true; // currently only functions because remap calls are currently not drawn! std::size_t draggedFunctionIndex; // function index if isDraggingFunction == true, else remap call index public: FunctionGraph(Dis8051Frame *mainFrame, wxWindow *parent, wxWindowID id); ~FunctionGraph() {} void RefreshCache(); private: void OnDraw(wxDC& dc); void OnLeftDown(wxMouseEvent &event); void OnMouseMove(wxMouseEvent &event); void OnLeftUp(wxMouseEvent &event); void OnLeftDClick(wxMouseEvent &event); void OnKeyDown(wxKeyEvent &event); void OnMouseWheel(wxMouseEvent &event); int getFunctionIndex(wxPoint mousePos); void DrawConnectorLine(wxDC *dc, int x1, int y1, int x2, int y2); DECLARE_EVENT_TABLE() }; #endif // FUNCTION_GRAPH_HPP_INCLUDED
2,867
C++
.h
76
33.644737
108
0.699026
msrst/interactive-8051-disassembler
39
5
1
GPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,877
scroll_overview.hpp
msrst_interactive-8051-disassembler/scroll_overview.hpp
/************************************************************************ * Copyright (C) 2020-2021 Matthias Rosenthal * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/> ***********************************************************************/ #ifndef SCROLL_OVERVIEW_HPP_INCLUDED #define SCROLL_OVERVIEW_HPP_INCLUDED #include "wx/scrolwin.h" class Dis8051Frame; class ScrollOverview : public wxScrolledWindow { private: Dis8051Frame *mainFrame; int w,h; public: ScrollOverview(Dis8051Frame *mainFrame, wxWindow *parent, wxWindowID id); ~ScrollOverview() {} private: void OnDraw(wxDC& dc); void OnLeftDown(wxMouseEvent &event); DECLARE_EVENT_TABLE() }; #endif // SCROLL_OVERVIEW_HPP_INCLUDED
1,285
C++
.h
33
36.424242
77
0.680064
msrst/interactive-8051-disassembler
39
5
1
GPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,878
annotation_canvas.hpp
msrst_interactive-8051-disassembler/annotation_canvas.hpp
/************************************************************************ * Copyright (C) 2020-2021 Matthias Rosenthal * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/> ***********************************************************************/ #ifndef ANNOTATION_CANVAS_HPP_INCLUDED #define ANNOTATION_CANVAS_HPP_INCLUDED #include "wx/scrolwin.h" class Dis8051Frame; class AnnotationCanvas : public wxWindow { private: Dis8051Frame *mainFrame; public: AnnotationCanvas(Dis8051Frame *mainFrame, wxWindow *parent, wxWindowID id); ~AnnotationCanvas() {} int lineHeight; bool annotateCalls = false; private: void OnPaint(wxPaintEvent &event); DECLARE_EVENT_TABLE(); }; #endif // ANNOTATION_CANVAS_HPP_INCLUDED
1,299
C++
.h
33
36.848485
79
0.68442
msrst/interactive-8051-disassembler
39
5
1
GPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,879
wxApp.h
msrst_interactive-8051-disassembler/wxApp.h
/************************************************************************ * Copyright (C) 2020-2021 Matthias Rosenthal * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/> ***********************************************************************/ #ifndef DISAS8051_APP_H_INCLUDED #define DISAS8051_APP_H_INCLUDED #include <wx/app.h> class Dis8051App : public wxApp { private: std::string firmwareFile; std::string metaFile; public: Dis8051App(); // for parsing the parameters passed from shell virtual void OnInitCmdLine(wxCmdLineParser &parser); virtual bool OnCmdLineParsed(wxCmdLineParser &parser); virtual bool OnInit(); virtual int OnExit(); }; #endif // DISAS8051_APP_H_INCLUDED
1,318
C++
.h
32
37.28125
74
0.65775
msrst/interactive-8051-disassembler
39
5
1
GPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,880
utils.hpp
msrst_interactive-8051-disassembler/utils/utils.hpp
/************************************************************************ * Copyright (C) 2020-2021 Matthias Rosenthal * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/> ***********************************************************************/ #ifndef P_UTILS_HPP_INCLUDED #define P_UTILS_HPP_INCLUDED #include <inttypes.h> #include <ctime> #include <string> #include <vector> #include <fstream> #include <map> #include <cmath> #include <stdexcept> #include <chrono> #include "../consts.hpp" std::string fn_Int_To_StringU(uint64_t i); std::string fn_Int_To_String(int64_t i); template<typename Tstr> // implemented for std::string and std::basic_string<uint8_t> std::string fn_FormatToHex(Tstr string, bool kleinbuchstaben); // Turns "abc" into "61 62 63" inline void fn_usleep(long long int us) { timespec t; t.tv_sec = us / 1000000; t.tv_nsec = (us % 1000000) * 1000; nanosleep(&t, NULL); } #define DATE_MIN_YEAR (1800) #define DATE_MAX_YEAR (2200) namespace utils { uint8_t Hex_To_uint8(char hex1, char hex2); // Upper and lower chars are possible std::string Format_Defaultdate_stdString(long long int datum, char ms_trennzeichen = ':'); std::string Format_Sec_Standarddatum_stdString(time_t datum); std::string Int_To_String(int64_t i); // Before an optional minus sign zeros are inserted so that the width equals to the width parameter. std::string Int_To_String_Zeros(long long int i, unsigned long int width); std::string Int_To_String_Hex(int64_t i, bool lowercase = true); // suffix _HexOk: "0x" at the begin is discarded and only the rest of the string is read as hex format. // suffix R: also fractions possible (p. e. 5/3). class string_to_int_converter { private: int fehler; public: string_to_int_converter(); private: void Init(); public: long long int ConvertToLLI(std::string rohstring); long long int ConvertToLLI_Hex(std::string rohstring); long long int ConvertToLLI_HexOk(std::string rohstring); // only hex if starting with 0x long long int ConvertToLLIFromSIt(std::string::iterator begin, std::string::iterator end); long long int ConvertToLLIFromSIt_Hex(std::string::iterator begin, std::string::iterator end); long long int ConvertToLLIFromSIt_HexOk(std::string::iterator begin, std::string::iterator end); // only hex if starting with 0x long long int ConvertToLLIFromSIt(std::string::iterator begin, std::string::iterator end, char tausender_zeichen); // Possible values when punct_char is '.': "5e-3", "5.2e+3", ".e-4" and "+5". double ConvertToDoubleFromSIt(std::string::iterator begin, std::string::iterator end, char punct_char = '.', char tausender_zeichen = ','); double ConvertToDoubleRFromSIt(std::string::iterator begin, std::string::iterator end, char punct_char = '.', char tausender_zeichen = ','); double ConvertToDouble(std::string rohstring, char punct_char = '.', char tausender_zeichen = ','); double ConvertToDoubleR(std::string rohstring, char punct_char = '.', char tausender_zeichen = ','); bool MistakeHappened(); int GetError() { return fehler; } }; class string_to_int_limited_converter: public string_to_int_converter { private: int limitfehler; public: string_to_int_limited_converter(); private: void Init(); public: long long int ConvertToLLI_Limited(std::string rohstring, long long int min, long long int max); long long int ConvertToLLI_Hex_Limited(std::string rohstring, long long int min, long long int max); long long int ConvertToLLI_HexOk_Limited(std::string rohstring, long long int min, long long int max); long long int ConvertToLLIFromSIt_Limited(std::string::iterator begin, std::string::iterator end, long long int min, long long int max); long long int ConvertToLLIFromSIt_Hex_Limited(std::string::iterator begin, std::string::iterator end, long long int min, long long int max); long long int ConvertToLLIFromSIt_HexOk_Limited(std::string::iterator begin, std::string::iterator end, long long int min, long long int max); double ConvertToDouble_Limited(std::string rohstring, double min, double max, char punct_char = '.', char tausender_zeichen = ','); double ConvertToDoubleR_Limited(std::string rohstring, double min, double max, char punct_char = '.', char tausender_zeichen = ','); bool LimitMistakeHappened(); int GetLimiterror() { return limitfehler; } }; bool GetFileString(std::string filename, std::string* value, bool binary = false); // value is overwritten, not appended. bool SetFileString(std::string filename, const std::string &value); bool str_begins_with(const std::string &str, const std::string &begin); bool str_ends_with(const std::string &str, const std::string &end); // chars durch chars ersetzen geht mit algorithm: std::replace void str_replace_char(std::string &str, char suchen, std::string ersetzen); std::vector<std::string> str_split(const std::string &str, const std::string &split); // The returned vector // contains at least one string (that is empty), even if str is empty. std::string str_to_upper(std::string str); // auch ä, ö, ü bool str_replace_one(std::string &str, const std::string &search, const std::string &replace); // true if found std::string vectorstring_unsplit(const std::vector<std::string> &array, char zeichen); std::string Char_To_UTF8String(uint32_t character); void Char_To_UTF8String(uint32_t character, std::string* str_ret); // appends the result to str_ret inline std::basic_string<uint8_t> StdStringToUstring(std::string str) { return std::basic_string<uint8_t>((uint8_t*)str.data(), str.length()); } inline std::string StdUstringToString(std::basic_string<uint8_t> str) { return std::string((char*)str.data(), str.length()); } std::string str_remove_sidewhites(const std::string &text); // Removes tabulators, spaces, line endings and \r at the first and at the last position. inline bool is_hexchar(char c) { return ((c >= '0') && (c <= '9')) || ((c >= 'A') && (c <= 'F')) || ((c >= 'a') && (c <= 'f')); } uint64_t GetTime_Microseconds(); // 100 years need 52 bit long long int GetTime_Milliseconds(); // 100 years beed 42 bit -> long long int required (-> 64 bit) double GetTimeAsDouble(); } // namespace utils #endif // P_UTILS_HPP_INCLUDED
6,973
C++
.h
126
51.587302
150
0.705319
msrst/interactive-8051-disassembler
39
5
1
GPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,881
utils_wx.h
msrst_interactive-8051-disassembler/utils/utils_wx.h
/************************************************************************ * Copyright (C) 2020-2021 Matthias Rosenthal * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/> ***********************************************************************/ #ifndef UTILS_WX_INCLUDED #define UTILS_WX_INCLUDED #include "wx/dc.h" #include "wx/dcmemory.h" #include "wx/string.h" #include "utils.hpp" namespace utils { wxString Format_Defaultdate_wxString(long long int datum); } // namespace utils wxString fn_Char_To_wxUTF8String(uint32_t zeichen); std::string fn_wxUTF8String_ToUTF8String(wxString string); // Unter Linux(Ubuntu), vielleicht auch unter Windows, ergibt // z. B. wxString(wxT("abc\x00e4sb")).c_str().AsChar() den String "" - diese Funktion konvertiert im Gegensatz dazu korrekt zu UTF8 // (ähnlich wie fn_winString_ToUTF8String) enum wxbuildinfoformat { wxbuildinfof_short_f, wxbuildinfof_long_f }; wxString fn_wxbuildinfo(wxbuildinfoformat format); #endif // UTILS_WX_INCLUDED
1,624
C++
.h
32
46.59375
167
0.669829
msrst/interactive-8051-disassembler
39
5
1
GPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,882
logger.hpp
msrst_interactive-8051-disassembler/utils/logger.hpp
/************************************************************************ * Copyright (C) 2020-2021 Matthias Rosenthal * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/> ***********************************************************************/ #ifndef LOGGER_HPP_INCLUDED #define LOGGER_HPP_INCLUDED #include <string> #include <boost/shared_ptr.hpp> namespace logger { class logger_base { public: virtual ~logger_base() {} virtual void LogError(std::string fehler) = 0; virtual void LogWarning(std::string warnung) = 0; virtual void LogInformation(std::string meldung) = 0; }; typedef boost::shared_ptr<logger_base> logger_base_ptr; } // namespace logger #endif // LOGGER_HPP_INCLUDED
1,267
C++
.h
31
38.612903
73
0.672372
msrst/interactive-8051-disassembler
39
5
1
GPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,883
logger.h
msrst_interactive-8051-disassembler/utils/logger.h
/************************************************************************ * Copyright (C) 2020-2021 Matthias Rosenthal * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/> ***********************************************************************/ /* * logger.h * default implementation of logger_base */ #ifndef dLOGGER_H_INCLUDED #define dLOGGER_H_INCLUDED #include <list> #include <string> #include <ctime> #include <fstream> #include <boost/thread/mutex.hpp> #ifdef GUI #define LOGGER_WXTEXTCTRL #endif #include "logger.hpp" #include "../consts.hpp" #ifdef LOGGER_WXTEXTCTRL #include "../gui/gui_palette.h" #endif namespace logger { enum class message_type { information = 0, warning, error }; enum class logdisplay_type { textctrl = 0, cout, file }; struct message { message_type type; std::string messageString; long long int time; }; class logdisplay { public: logdisplay_type type; virtual ~logdisplay() {} virtual void newLine(message &newMessage) = 0; virtual void beginUpdate() {} virtual void endUpdate() {} }; #ifdef LOGGER_WXTEXTCTRL class logdisplay_textctrl: public logdisplay { public: wxTextCtrl* m_textctrl; gui_palette* m_gui_palette; virtual ~logdisplay_textctrl() {} virtual void newLine(message &newMessage); }; #endif // LOGGER_WXTEXTCTRL class logdisplay_cout: public logdisplay { public: virtual ~logdisplay_cout() {} virtual void newLine(message &newMessage); }; class logdisplay_file: public logdisplay { public: std::string filename; std::ofstream file; bool isFileOpen; logdisplay_file(); virtual ~logdisplay_file() {} virtual void newLine(message &newMessage); virtual void beginUpdate(); virtual void endUpdate(); }; class logger: public logger_base { private: boost::mutex messagesLock; std::list<message> messages; boost::mutex newMessagesLock; std::list<message> newMessages; std::list<logdisplay*> logdisplays; public: logger(); virtual ~logger(); virtual void LogError(std::string msg); virtual void LogInformation(std::string msg); virtual void LogWarning(std::string msg); #ifdef LOGGER_WXTEXTCTRL void AddLogDisplay(wxTextCtrl* textctrl, gui_palette* c_gui_palette); #endif void AddLogDisplay_cout(); void AddLogDisplay(std::string dateiname); void updateLogDisplays(); private: void registerMessage(message &newMessage); }; } // namespace logger #endif // dLOGGER_H_INCLUDED
3,190
C++
.h
115
23.826087
74
0.680039
msrst/interactive-8051-disassembler
39
5
1
GPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,884
gui_palette.h
msrst_interactive-8051-disassembler/gui/gui_palette.h
/************************************************************************ * Copyright (C) 2020-2021 Matthias Rosenthal * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/> ***********************************************************************/ #ifndef GUI_PALETTE_H_INCLUDED #define GUI_PALETTE_H_INCLUDED #include "wx/wx.h" struct gui_palette { wxString textextent_teststring; wxColour backgroundcolour_frame; wxPen backgroundcolour_frame_pen; wxBrush backgroundcolour_frame_brush; wxTextAttr logger_textctrl_error_textattr; wxTextAttr logger_textctrl_warning_textattr; wxTextAttr logger_textctrl_message_textattr; wxTextAttr default_textctrl_textattr; }; void gui_palette_init(gui_palette& gui_palette); void gui_palette_end(gui_palette& gui_palette); #endif // GUI_PALETTE_H_INCLUDED
1,422
C++
.h
31
41.903226
74
0.680959
msrst/interactive-8051-disassembler
39
5
1
GPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,885
ignore_block.hpp
msrst_interactive-8051-disassembler/8051/ignore_block.hpp
/************************************************************************ * Copyright (C) 2020-2021 Matthias Rosenthal * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/> ***********************************************************************/ #ifndef IGNORE_BLOCK_8051_HPP_INCLUDED #define IGNORE_BLOCK_8051_HPP_INCLUDED namespace disas8051 { // represents a code block which is ignored by the disassembler class IgnoreBlock { public: // maybe insert an optional end address here sometime }; } // namespace disas8051 #endif // IGNORE_BLOCK_8051_HPP_INCLUDED
1,154
C++
.h
26
41.384615
74
0.662489
msrst/interactive-8051-disassembler
39
5
1
GPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,886
function.hpp
msrst_interactive-8051-disassembler/8051/function.hpp
/************************************************************************ * Copyright (C) 2020-2021 Matthias Rosenthal * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/> ***********************************************************************/ #ifndef FUNCTION_8051_HPP_INCLUDED #define FUNCTION_8051_HPP_INCLUDED #include <string> #include <inttypes.h> #include <vector> namespace disas8051 { class Function { public: std::string name; int posX, posY; // for graph in GUI bool isInterrupt; uint64_t endAddress; // address after the last instruction bool isShownInGraph = true; Function() = default; Function(std::string name, bool isInterrupt = false, int posX = 10, int posY = 10) { this->name = name; this->isInterrupt = isInterrupt; this->posX = posX; this->posY = posY; // the other params are parsed by disassembler/disassembly } struct Block { uint64_t begin; uint64_t end; // address after the last instruction bool contains(uint64_t address) const { return (address >= begin) && (address < end); } }; std::vector<Block> blocks; bool contains(uint64_t address); std::string getBlockSummary(); // sometimes, e. g. when jumping to another part of the function, the current block // is ended but one instruction later the function continues with another block. // This function resolves that. void defragmentBlocks(); }; } // namespace disas8051 #endif // FUNCTION_8051_HPP_INCLUDED
2,027
C++
.h
55
34.109091
85
0.689744
msrst/interactive-8051-disassembler
39
5
1
GPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,887
disassembler.hpp
msrst_interactive-8051-disassembler/8051/disassembler.hpp
/************************************************************************ * Copyright (C) 2020-2021 Matthias Rosenthal * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/> ***********************************************************************/ #ifndef DISASSEMBLER_8051_HPP_INCLUDED #define DISASSEMBLER_8051_HPP_INCLUDED #include <string> #include <memory> #include "disassembly.hpp" namespace disas8051 { enum { NONE = 0, ADDR11 = 1, // 8 bits from argument + 3 high bits from opcode ADDR16 = 2, // A 16-bit address destination. Used by LCALL and LJMP DIRECT = 3, // An internal data RAM location (0-127) or SFR (128-255). IMMED = 4, // Immediate value (literal) - 8 Bit IMMED16 = 5, // Immediate Value (16 bit) BIT = 6, // A bit within one of the bitfield bytes OFFSET = 7, // same as direct? A = 8, // Accum directly. Used only for second arg for a few ops C = 9, // C IR0 = 10, // @R0 IR1 = 11, // @R1 R0 = 12, // R0 R1 = 13, // R1 R2 = 14, // R2 R3 = 15, // R3 R4 = 16, // R4 R5 = 17, // R5 R6 = 18, // R6 R7 = 19 // R7 }; struct Instruct8051 { const char *name; //static portion of the decoded instruction int length; //# of bytes this instruction spans int arg1; //Type of the first argument int arg2; //Type of the second argument bool isJump; //Does this instruction always jump bool isCondJump; //Does this instruction maybe branch? (also calls) }; //all 256 op codes extern Instruct8051 OpCodes[]; //Starting at 0x80 and going through 0xFF these are the SFR's for a ENE KB9012 extern const char *SFR[]; class Disassembler { private: logger::logger_base *logger; public: Disassembler(logger::logger_base *logger); Instruction disassembleInstruction(const ustring &buf, uint64_t address); void followCodePath(const ustring &buf, uint64_t startAddress, Disassembly *disassembly); private: int interpretArgument(int32_t *outInt, const uint8_t *inBuffer, int opType, uint32_t address, int op); int32_t resolveAddress(int32_t rawAddress, uint32_t currentAddress); // calculates the actual address (resolving X-Bus remappings) void disassembleSwitchStatement(const ustring &buf, uint64_t callAddress, uint64_t startAddress, bool isI16Switch, Disassembly *disassembly); }; } // namespace disas8051 #endif // DISASSEMBLER_8051_HPP_INCLUDED
2,991
C++
.h
71
39.661972
142
0.671261
msrst/interactive-8051-disassembler
39
5
1
GPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,888
remap_call.hpp
msrst_interactive-8051-disassembler/8051/remap_call.hpp
/************************************************************************ * Copyright (C) 2020-2021 Matthias Rosenthal * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/> ***********************************************************************/ #ifndef REMAP_CALL_HPP_INCLUDED #define REMAP_CALL_HPP_INCLUDED namespace disas8051 { class RemapCall { public: uint64_t targetAddress; // -1 if invalid remap call int posX, posY; // for graph in GUI, currently unused! }; } // namespace disas8051 #endif // REMAP_CALL_HPP_INCLUDED
1,124
C++
.h
26
40.076923
74
0.647654
msrst/interactive-8051-disassembler
39
5
1
GPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,889
disassembly.hpp
msrst_interactive-8051-disassembler/8051/disassembly.hpp
/************************************************************************ * Copyright (C) 2020-2021 Matthias Rosenthal * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/> ***********************************************************************/ #ifndef DISASSEMBLY_8051_HPP_INCLUDED #define DISASSEMBLY_8051_HPP_INCLUDED #include <map> #include <vector> #include <unordered_map> #include <inttypes.h> #include "../utils/logger.h" #include "instruction.hpp" #include "function.hpp" #include "remap_call.hpp" #include "ignore_block.hpp" #include "switch_statement.hpp" namespace disas8051 { class Disassembler; class Disassembly { private: logger::logger_base *logger; std::map<uint64_t, std::string> pendingComments; // stores comments after reading the meta file before calling resolveComments() wxStyledTextCtrl *textCtrl; public: Disassembly(logger::logger_base *logger) { this->logger = logger; } ustring buf; // must be set by user before printing std::map<uint64_t, IgnoreBlock> ignoreBlocks; std::map<uint64_t, Instruction> instructions; std::unordered_map<uint64_t, std::vector<uint64_t>> jumpTargets; // target address, source addresses std::map<uint64_t, Function> functions; std::map<uint64_t, RemapCall> remapCalls; std::vector<SwitchStatement> switchStatements; std::map<uint64_t, int> caseBlocks; // the integer is the switchStatement index std::map<int, uint64_t> addressByLine; // for text ctrl void printToWx(wxStyledTextCtrl *textCtrl); // stores the pointer for referral, e. g. in updateFunctionName int findLineByAddress(int address); // returns -1 if address out of range, this function is very costly int openMetaFile(std::string filename); int saveMetaFile(std::string filename); void resolveRemapCalls(Disassembler *disassembler); // if the address or the target address is not already disassembled, this is also done here. void resolveComments(); // applies all comments read from the meta file to the instructions void autoComment(); void resolveFunctionEndAddresses(); void addFunction(int address, Function function); // also disassembles the new function, if necessary (with a new disassembler) void updateFunctionName(int address, std::string newName); void updateInstructionComment(int address, std::string newComment); void deleteFunction(int address); std::map<uint64_t, Function>::iterator findFunction(int addressIn); std::vector<uint64_t> GetFunctionTargetAddresses(uint64_t functionAddress); bool seemsToBeInvalidCode(uint64_t address); // false if called with invalid address std::string formatWithFunction(uint64_t address); // e. g. "1ab8 (myfunc)" int findSwitchStatementOnExact(uint64_t address); // returns -1 if not found, else the index of the switch statement private: void updateLineAtAddress(int address); void recurseFunction(std::map<uint64_t, Function>::iterator itFunction, std::map<uint64_t, Function>::iterator itNextFunction, uint64_t address); }; } // namespace disas8051 #endif // DISASSEMBLY_8051_HPP_INCLUDED
3,702
C++
.h
70
49.128571
149
0.731422
msrst/interactive-8051-disassembler
39
5
1
GPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,890
instruction.hpp
msrst_interactive-8051-disassembler/8051/instruction.hpp
/************************************************************************ * Copyright (C) 2020-2021 Matthias Rosenthal * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/> ***********************************************************************/ #ifndef INSTRUCTION_8051_HPP_INCLUDED #define INSTRUCTION_8051_HPP_INCLUDED #include <string> #include "wx/version.h" class wxStyledTextCtrl; #if wxCHECK_VERSION(3, 1, 0) // this removes a depracted warning #define TEXTCTRL_START_STYLING(textCtrl, pos) (textCtrl)->StartStyling(pos) #else // StartStyling(pos) is not available in older wx versions #define TEXTCTRL_START_STYLING(textCtrl, pos) (textCtrl)->StartStyling(pos, 0xff) #endif namespace disas8051 { enum class Styles : int { DEFAULT = 0, BUF_ADDRESS, BYTES, RET_INSTRUCTION, COMMENT }; typedef std::basic_string<uint8_t> ustring; class Instruction { public: uint8_t opNum; int length; int32_t arg1; int arg1Type; int32_t arg2; int arg2Type; bool isJump; bool isCondJump; uint64_t address; std::string autocomment; std::string comment; void ac(std::string c); // adds an autocomment std::string getFullComment(); std::string getName(); bool isCall(); std::string formatSimple(); void printToWx(wxStyledTextCtrl *textCtrl); void printToWx(wxStyledTextCtrl *textCtrl, int pos); }; } // namespace disas8051 #endif // INSTRUCTION_8051_HPP_INCLUDED
2,003
C++
.h
59
31.033898
81
0.693624
msrst/interactive-8051-disassembler
39
5
1
GPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,891
switch_statement.hpp
msrst_interactive-8051-disassembler/8051/switch_statement.hpp
/************************************************************************ * Copyright (C) 2020-2021 Matthias Rosenthal * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/> ***********************************************************************/ #ifndef SWITCH_STATEMENT_8051_HPP_INCLUDED #define SWITCH_STATEMENT_8051_HPP_INCLUDED #include <string> #include <vector> #include <inttypes.h> namespace disas8051 { class SwitchStatement { public: uint64_t address; // this is the address of the call of the CCASE or ICASE function. bool isI16; // whether it is "switched" for 8- or 16-bit values static const int32_t DEFAULT_CASE_VALUE = 0x10000; // this is ok because we only have 16- and 8-bit switches struct Case { int32_t value; // it's a default case if this value equals DEFAULT_CASE_VALUE uint64_t address; }; std::vector<Case> cases; uint64_t getDataLength() { if(isI16) { return cases.size() * 4; } else { return cases.size() * 3 + 1; // the default case takes always 4 bytes } } struct ValuesCase { std::vector<int32_t> values; uint64_t address; ValuesCase(int32_t value, uint64_t address) { values.push_back(value); this->address = address; } std::string formatValues(); }; std::vector<ValuesCase> groupCasesByValues() const; }; } // namespace disas8051 #endif // SWITCH_STATEMENT_8051_HPP_INCLUDED
2,001
C++
.h
55
32.618182
110
0.668237
msrst/interactive-8051-disassembler
39
5
1
GPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,892
Freshycalls_PoC.cpp
crummie5_Freshycalls_PoC/Freshycalls_PoC.cpp
// Copyright (c) 2020 ElephantSe4l. All Rights Reserved. // Released under MPL-2.0, see LICENCE for more information. #include "syscall/syscall.hpp" #include <iostream> #include <string> #include <cstdint> #include <Windows.h> #include <winternl.h> #include "processsnapshot.h" #include <DbgHelp.h> #pragma comment (lib, "Dbghelp.lib") static auto &syscall = freshycalls::Syscall::get_instance(); BOOL CALLBACK SnapshotCallback(PVOID CallbackParam, PMINIDUMP_CALLBACK_INPUT CallbackInput, PMINIDUMP_CALLBACK_OUTPUT CallbackOutput) { switch (CallbackInput->CallbackType) { case 16: // IsProcessSnapshotCallback CallbackOutput->Status = S_FALSE; break; } return TRUE; } std::wstring StrToWStr(std::string_view str) { int no_chars = MultiByteToWideChar(CP_UTF8, 0, str.data(), str.length(), nullptr, 0); std::wstring wstr(no_chars, 0); MultiByteToWideChar(CP_UTF8, 0, str.data(), str.length(), LPWSTR(wstr.data()), no_chars); return wstr; } void ActivateSeDebug() { HANDLE token_handle{}; TOKEN_PRIVILEGES token_privileges{}; syscall.CallSyscall("NtOpenProcessToken", HANDLE(-1), TOKEN_ADJUST_PRIVILEGES, &token_handle) .OrDie("[ActiveSeDebug] An error happened while opening the current process token: \"{{result_msg}}\" (Error Code: {{result_as_hex}})"); token_privileges.PrivilegeCount = 1; // SeDebug's LUID low part == 20 token_privileges.Privileges[0].Luid = {20L, 0}; token_privileges.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; syscall.CallSyscall("NtAdjustPrivilegesToken", token_handle, false, &token_privileges, sizeof(TOKEN_PRIVILEGES), nullptr, nullptr) .OrDie("[ActiveSeDebug] An error happened while activating SeDebug on current token: \"{{result_msg}}\" (Error Code: {{result_as_hex}})"); CloseHandle(token_handle); } HANDLE OpenProcess(uint32_t process_id) { HANDLE process_handle{}; OBJECT_ATTRIBUTES obj{}; InitializeObjectAttributes(&obj, nullptr, 0, nullptr, nullptr); CLIENT_ID client = {reinterpret_cast<HANDLE>(static_cast<DWORD_PTR>(process_id)), nullptr}; syscall.CallSyscall("NtOpenProcess", &process_handle, PROCESS_CREATE_PROCESS | PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION | PROCESS_VM_READ | PROCESS_DUP_HANDLE, &obj, &client) .OrDie("[OpenProcess] An error happened while opening the target process: \"{{result_msg}}\" (Error Code: {{result_as_hex}})"); return process_handle; } HANDLE CreateDumpFile(std::string_view file_path) { HANDLE file_handle{}; IO_STATUS_BLOCK isb{}; OBJECT_ATTRIBUTES obj{}; UNICODE_STRING ntpath{}; using FunctionDef = bool (__stdcall *)(PCWSTR, PUNICODE_STRING, PCWSTR *, VOID *); FunctionDef RtlDosPathNameToNtPathName_U = reinterpret_cast<decltype(RtlDosPathNameToNtPathName_U)>(GetProcAddress(GetModuleHandle(L"ntdll.dll"), "RtlDosPathNameToNtPathName_U")); bool status = RtlDosPathNameToNtPathName_U(StrToWStr(file_path).data(), &ntpath, nullptr, nullptr); if (!status) { throw std::runtime_error(freshycalls::utils::FormatString("[CreateDumpFile] RtlDosPathNameToNtPathName_U failed: \"%s\" (Error Code: %ld)", freshycalls::utils::GetErrorMessage(GetLastError()).data(), GetLastError())); } InitializeObjectAttributes(&obj, &ntpath, OBJ_CASE_INSENSITIVE, nullptr, nullptr); syscall.CallSyscall("NtCreateFile", &file_handle, FILE_GENERIC_WRITE, &obj, &isb, nullptr, FILE_ATTRIBUTE_NORMAL, FILE_SHARE_WRITE, FILE_OVERWRITE_IF, FILE_RANDOM_ACCESS | FILE_NON_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT, nullptr, 0) .OrDie("[CreateDumpFile] An error happened while creating the dump file (Error Code: {{result_as_hex}})"); return file_handle; } void Usage() { std::cerr << "FreshyCalls' PoC dumper usage: " << std::endl << std::endl; std::cerr << "\tdumper.exe -pid <process_id> <output_file>" << std::endl << std::endl; } uint32_t GetPID(int argc, char *argv[]) { if (argc < 4) { Usage(); exit(-1); } if (std::string(argv[1]) == "-pid") { return std::stoul(argv[2], nullptr, 10); } Usage(); exit(-1); } int main(int argc, char *argv[]) { HANDLE process_handle; HANDLE file_handle; const uint32_t process_id = GetPID(argc, argv); std::cout << "FreshyCalls' PoC dumper" << std::endl << std::endl; try { std::cout << "[+] Trying to activate SeDebug..."; ActivateSeDebug(); std::cout << " OK!" << std::endl; std::cout << "[+] Trying to open the process (PID: " << process_id << ")..."; process_handle = OpenProcess(process_id); std::cout << " OK!" << std::endl; std::cout << "[+] Trying to create the dump file..."; file_handle = CreateDumpFile(argv[3]); std::cout << " OK!" << std::endl; const uint32_t capture_flags = PSS_CAPTURE_VA_CLONE | PSS_CAPTURE_THREADS | PSS_CAPTURE_THREAD_CONTEXT | PSS_CREATE_RELEASE_SECTION; HPSS snapshot_handle; std::cout << "[+] Trying to create a snapshot of the process..."; const uint32_t snapshot_status = PssCaptureSnapshot(process_handle, PSS_CAPTURE_FLAGS(capture_flags), CONTEXT_ALL, &snapshot_handle); if (snapshot_status != 0) { std::cerr << freshycalls::utils::FormatString("An error happened while creating the snapshot of the target process: %s (Error Code: %#010x)", freshycalls::utils::GetErrorMessage(snapshot_status).data(), snapshot_status); std::cerr << std::endl; exit(-1); } std::cout << " OK!" << std::endl; MINIDUMP_CALLBACK_INFORMATION callback_info = {&SnapshotCallback, nullptr}; std::cout << "[+] Trying to dump the snapshot..."; if (!MiniDumpWriteDump(snapshot_handle, process_id, file_handle, MiniDumpWithFullMemory, nullptr, nullptr, &callback_info)) { std::cerr << freshycalls::utils::FormatString("An error happened while dumping the snapshot of the target process: %s (Error Code: %#010x)", freshycalls::utils::GetErrorMessage(GetLastError()).data(), GetLastError()); std::cerr << std::endl; exit(-1); } std::cout << " OK!" << std::endl; } catch (const std::runtime_error &e) { std::cerr << std::endl << e.what() << std::endl; exit(-1); } std::cout << std::endl << "Dump at " << argv[3] << std::endl; std::cout << "Enjoy!" << std::endl; return 0; }
6,760
C++
.cpp
139
41.338129
147
0.644397
crummie5/Freshycalls_PoC
39
6
0
MPL-2.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,893
SptHviewInterface.cpp
ASTex-ICube_semiproctex/Semiproc_synthesis_Src/SptSynthesizer/SptHviewInterface.cpp
/* * Publication: Semi-Procedural Textures Using Point Process Texture Basis Functions * Computer Graphics Forum (EGSR 2020 special issue) * Authors: P. Guehl , R. AllEgre , J.-M. Dischler, B. Benes , and E. Galin * * Code author: Pascal Guehl */ /** * @version 1.0 */ #include "SptHviewInterface.h" /****************************************************************************** ******************************* INCLUDE SECTION ****************************** ******************************************************************************/ // Project #include "SptImageHelper.h" // System #include <cassert> // STL #include <iostream> #include <algorithm> #include <functional> #include <numeric> // HVIEW #include "hvPicture.h" /****************************************************************************** ****************************** NAMESPACE SECTION ***************************** ******************************************************************************/ // Project using namespace Spt; /****************************************************************************** ************************* DEFINE AND CONSTANT SECTION ************************ ******************************************************************************/ /****************************************************************************** ***************************** TYPE DEFINITION ******************************** ******************************************************************************/ /****************************************************************************** ***************************** METHOD DEFINITION ****************************** ******************************************************************************/ /****************************************************************************** * Constructor ******************************************************************************/ SptHviewInterface::SptHviewInterface() // hview synthesis parameters : mName() , mSTOPATLEVEL( 0 ) , mPosx( 0 ) , mPosy( 0 ) //, mExample() //, mExdist() , mWeight( 0. ) , mPowr( 0. ) , mIndweight( 0.f ) , mNeighbor( 0 ) , mAtlevel( 0 ) , mBsize( 0 ) , mERR( 0.f ) //, mMask() //, mGuidance() //, mIndex() //, mRes() { } /****************************************************************************** * Destructor ******************************************************************************/ SptHviewInterface::~SptHviewInterface() { } /****************************************************************************** * Initialize ******************************************************************************/ void SptHviewInterface::initialize() { } /****************************************************************************** * Finalize ******************************************************************************/ void SptHviewInterface::finalize() { } /****************************************************************************** * Launch the synthesis pipeline ******************************************************************************/ void SptHviewInterface::execute() { // User customizable parameter(s) const int nbCorrectionPasses = 2; const bool useSmartInitialization = false; // Parameter conversion: // // GUIDE 0.9 <=> guidanceWeight // STRENGTH 0.5 // INITLEVEL 2 <=> pyramidMaxLevel // BLOCSIZE 64 <=> mSmartInitNbPasses (pb: can be any value!) // INITERR 100 <=> initializationError (per-pixel threshold error in a block to keep it or not, % in [0;1]) // INDEXWEIGHT 0 <=> correctionLabelErrorAmount (3x²) // Call hview texture synthesis api mRes.execute_semiProceduralTextureSynthesis( mName.c_str(), mSTOPATLEVEL, // should be 0 (for debug purpose only: can stop synthesis a given coarse level) mPosx, mPosy, // translation used to be able to tie tiles for large textrues mExample, mExdist, // exemplar mWeight, // weight color vs distance when searching for neighborhood candidates (i.e. new pixels) mPowr, mIndweight, mNeighbor, mAtlevel, mBsize, mERR, mMask, mGuidance, mIndex, // user customizable parameter(s) nbCorrectionPasses, useSmartInitialization ); } /****************************************************************************** * * Load exemplar (color texture) * * @param pFilename ******************************************************************************/ void SptHviewInterface::loadExemplar( const char* pFilename ) { // Read image int width = 0; int height = 0; int nrChannels = 0; const int desired_channels = 0; // TODO: handle this parameter! unsigned char* pData = nullptr; SptImageHelper::loadImage( pFilename, width, height, nrChannels, pData, desired_channels ); // Store data in hview container: mExample // TODO // ... } /****************************************************************************** * Load structure map (binary) * * @param pFilename ******************************************************************************/ void SptHviewInterface::loadExemplarStructureMap( const char* pFilename ) { // Read image int width = 0; int height = 0; int nrChannels = 0; const int desired_channels = 0; // TODO: handle this parameter! unsigned char* pData = nullptr; SptImageHelper::loadImage( pFilename, width, height, nrChannels, pData, desired_channels ); // Store data in hview container // TODO // ... } /****************************************************************************** * Load distance map * * @param pFilename ******************************************************************************/ void SptHviewInterface::loadExemplarDistanceMap( const char* pFilename ) { // Read image int width = 0; int height = 0; int nrChannels = 0; const int desired_channels = 0; // TODO: handle this parameter! unsigned char* pData = nullptr; SptImageHelper::loadImage( pFilename, width, height, nrChannels, pData, desired_channels ); // Store data in hview container: mExdist // TODO // ... } /****************************************************************************** * Load label map * * @param pFilename ******************************************************************************/ void SptHviewInterface::loadExemplarLabelMap( const char* pFilename ) { // Read image int width = 0; int height = 0; int nrChannels = 0; const int desired_channels = 0; // TODO: handle this parameter! unsigned char* pData = nullptr; SptImageHelper::loadImage( pFilename, width, height, nrChannels, pData, desired_channels ); // Store data in hview container // TODO // ... } /****************************************************************************** * Load guidance PPTBF * * @param pFilename ******************************************************************************/ void SptHviewInterface::loadGuidancePPTBF( const char* pFilename ) { // Read image int width = 0; int height = 0; int nrChannels = 0; const int desired_channels = 0; // TODO: handle this parameter! unsigned char* pData = nullptr; SptImageHelper::loadImage( pFilename, width, height, nrChannels, pData, desired_channels ); // Store data in hview container // TODO // ... } /****************************************************************************** * Load guidance mask * * @param pFilename ******************************************************************************/ void SptHviewInterface::loadGuidanceMask( const char* pFilename ) { // Read image int width = 0; int height = 0; int nrChannels = 0; const int desired_channels = 0; // TODO: handle this parameter! unsigned char* pData = nullptr; SptImageHelper::loadImage( pFilename, width, height, nrChannels, pData, desired_channels ); // Store data in hview container // TODO // ... } /****************************************************************************** * Load guidance distance map * * @param pFilename ******************************************************************************/ void SptHviewInterface::loadGuidanceDistanceMap( const char* pFilename ) { // Read image int width = 0; int height = 0; int nrChannels = 0; const int desired_channels = 0; // TODO: handle this parameter! unsigned char* pData = nullptr; SptImageHelper::loadImage( pFilename, width, height, nrChannels, pData, desired_channels ); // Store data in hview container // TODO // ... } /****************************************************************************** * Load guidance label map * * @param pFilename ******************************************************************************/ void SptHviewInterface::loadGuidanceLabelMap( const char* pFilename ) { // Read image int width = 0; int height = 0; int nrChannels = 0; const int desired_channels = 0; // TODO: handle this parameter! unsigned char* pData = nullptr; SptImageHelper::loadImage( pFilename, width, height, nrChannels, pData, desired_channels ); // Store data in hview container // TODO // ... }
8,999
C++
.cpp
257
33.171206
112
0.465709
ASTex-ICube/semiproctex
39
8
2
LGPL-2.1
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,894
SptImageHelper.cpp
ASTex-ICube_semiproctex/Semiproc_synthesis_Src/SptSynthesizer/SptImageHelper.cpp
/* * Publication: Semi-Procedural Textures Using Point Process Texture Basis Functions * Computer Graphics Forum (EGSR 2020 special issue) * Authors: P. Guehl , R. AllEgre , J.-M. Dischler, B. Benes , and E. Galin * * Code author: Pascal Guehl */ /** * @version 1.0 */ #include "SptImageHelper.h" /****************************************************************************** ******************************* INCLUDE SECTION ****************************** ******************************************************************************/ // stb #define STB_IMAGE_IMPLEMENTATION #define STB_IMAGE_WRITE_IMPLEMENTATION #include <stb_image.h> #include <stb_image_write.h> /****************************************************************************** ****************************** NAMESPACE SECTION ***************************** ******************************************************************************/ /****************************************************************************** ************************* DEFINE AND CONSTANT SECTION ************************ ******************************************************************************/ /****************************************************************************** ***************************** TYPE DEFINITION ******************************** ******************************************************************************/ /****************************************************************************** ***************************** METHOD DEFINITION ****************************** ******************************************************************************/ // Project using namespace Spt; /****************************************************************************** * Load image ******************************************************************************/ void SptImageHelper::loadImage( const char* pFilename, int& pWidth, int& pHeight, int& pNrChannels, unsigned char*& pData, int desired_channels ) { stbi_set_flip_vertically_on_load( 1 ); pData = stbi_load( pFilename, &pWidth, &pHeight, &pNrChannels, desired_channels ); } /****************************************************************************** * Free image data ******************************************************************************/ void SptImageHelper::freeImage( unsigned char* pData ) { // Free memory stbi_image_free( pData ); } /****************************************************************************** * Save image ******************************************************************************/ int SptImageHelper::saveImage( const char* pFilename, const int pWidth, const int pHeight, const int pNrChannels, const void* pData ) { const void* data = pData; const int stride_in_bytes = pNrChannels * pWidth; stbi_flip_vertically_on_write( 1 ); int status = stbi_write_png( pFilename, pWidth, pHeight, pNrChannels, data, stride_in_bytes ); return status; }
2,973
C++
.cpp
60
47.733333
145
0.34334
ASTex-ICube/semiproctex
39
8
2
LGPL-2.1
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,895
main.cpp
ASTex-ICube_semiproctex/Semiproc_synthesis_Src/SptSynthesizer/main.cpp
/* * Publication: Semi-Procedural Textures Using Point Process Texture Basis Functions * Computer Graphics Forum (EGSR 2020 special issue) * Authors: P. Guehl , R. AllEgre , J.-M. Dischler, B. Benes , and E. Galin * * Code author: Pascal Guehl */ /** * @version 1.0 */ /****************************************************************************** ******************************* INCLUDE SECTION ****************************** ******************************************************************************/ // Project #include "SptSynthesizer.h" #include "SptBasicSynthesizer.h" // STL #include <string> #include <fstream> #include <iostream> #include <vector> #include <sstream> // System #include <cstdlib> #include <ctime> #include <cassert> /****************************************************************************** ****************************** NAMESPACE SECTION ***************************** ******************************************************************************/ /****************************************************************************** ************************* DEFINE AND CONSTANT SECTION ************************ ******************************************************************************/ /** * Basic software synthesizer * * SptBasicSynthesizer is a basic synthesizer that only requires 3 files: * - an input exemplar name xxx_scrop.png * - an input segmented exemplar name xxx_seg_scrop.png * - a pptbf parameters file xxx_seg_scrop_pptbf_params.txt * where xxx is texture name. */ #define _USE_BASIC_SYNTHESIZER_ /****************************************************************************** ***************************** TYPE DEFINITION ******************************** ******************************************************************************/ /****************************************************************************** ***************************** METHOD DEFINITION ****************************** ******************************************************************************/ //----------------------------------------------------------------------------- // SOFTWARE INPUT //----------------------------------------------------------------------------- // //1) 2 images of PPTBF (pptbf in grey levels + random pptbf labels at feature points (in grey level also?) // //2) 3 images of exemplar: color + binary structure + les labels // //3) 1 file containg numperical valeus of parameters : //- threshold //- synthesis parameters (smart init, neighborhoods, errors, etc.) // //The batch software load these files (5 images + 1 file) et generates the synthesis. // // To sumplify data management when loading multiple files, // data MUST respect a strict naming convention : // // the SemiProcTexProject.exe software works by providing a semi-procedural texture file as parameter, such as : //C:\PPTBF\Bin\SemiProcTexProject.exe C : \PPTBF\Data\Matching_structures\cells\TexturesCom_FloorsRounded0112_S_v2_scrop_synthesis_params.txt // BEWARE : required data MUST be in same directory than parameter file : // - xxx_scrop.png(input exemplar) // - xxx_seg_scrop.png(binary structure of input exemplar) // - xxx_scrop_semiproctex_pptbf_params.txt(PPTBF parameter file of input exemplar) // - xxx_scrop_synthesis_params.txt(semi - procedural texture parameter file of input exemplar) /****************************************************************************** * Main entry program * * @param pArgc Number of arguments * @param pArgv List of arguments * * @return flag telling whether or not it succeeds ******************************************************************************/ int main( int pArgc, char** pArgv ) { // Log info std::cout << "---------------------------------" << std::endl; std::cout << "- SemiProcTex Synthesizer Tool --" << std::endl; std::cout << "---------------------------------" << std::endl; // Check command line arguments #ifndef _USE_BASIC_SYNTHESIZER_ const int nbArguments = 1; if ( pArgc < ( 1 + nbArguments ) ) { // Log info std::cout << "Error: waiting for " << nbArguments << " parameter(s)" << std::endl; std::cout << " ex: program semiProcTex_params.txt"<< std::endl; // Exit return -1; } #else // Example: SptBasicSynthesizer.exe cracked_asphalt_160796 0.9 0.5 2 64 100 0.0 const int nbArguments = 7; if ( pArgc < ( 1 + nbArguments ) ) { // Log info std::cout << "Error: waiting for " << nbArguments << " parameter(s)" << std::endl; std::cout << " ex: program textureName GUIDE STRENGTH INITLEVEL BLOCSIZE INITERR INDEXWEIGHT" << std::endl; // Exit return -1; } #endif // Retrieve program directory int indexParameter = 0; std::string workingDirectory = ""; workingDirectory = pArgv[ indexParameter++ ]; // User customizable parameters : retrieve command line parameters #ifndef _USE_BASIC_SYNTHESIZER_ const char* semiProcTexConfigFilename = pArgv[ indexParameter++ ]; #else const char* textureName = pArgv[ indexParameter++ ]; std::string mExemplarName = std::string( textureName ); float GUIDE = std::stof( pArgv[ indexParameter++ ] ); // default: 0.99 float STRENGTH = std::stof( pArgv[ indexParameter++ ] ); // default: 0.5 int INITLEVEL = std::stoi( pArgv[ indexParameter++ ] ); // default: 0 int BLOCSIZE = std::stoi( pArgv[ indexParameter++ ] ); // default: 0 float INITERR = std::stof( pArgv[ indexParameter++ ] ); // default: 0.5 float INDEXWEIGHT = std::stof( pArgv[ indexParameter++ ] ); // default: 0.5 #endif // Initialization #ifndef _USE_BASIC_SYNTHESIZER_ Spt::SptSynthesizer* semiProcTexSynthesizer = new Spt::SptSynthesizer(); #else Spt::SptBasicSynthesizer* semiProcTexSynthesizer = new Spt::SptBasicSynthesizer(); #endif // - initialize resources semiProcTexSynthesizer->initialize(); #ifndef _USE_BASIC_SYNTHESIZER_ // Load synthesis parameters int errorStatus = semiProcTexSynthesizer->loadParameters( semiProcTexConfigFilename ); assert( errorStatus != -1 ); #else // Set synthesis parameters semiProcTexSynthesizer->setExemplarName( mExemplarName.c_str() ); semiProcTexSynthesizer->setGUIDE( GUIDE ); semiProcTexSynthesizer->setSTRENGTH( STRENGTH ); semiProcTexSynthesizer->setINITLEVEL( INITLEVEL ); semiProcTexSynthesizer->setBLOCSIZE( BLOCSIZE ); semiProcTexSynthesizer->setINITERR( INITERR ); semiProcTexSynthesizer->setINDEXWEIGHT( INDEXWEIGHT ); #endif // Launch synthesis semiProcTexSynthesizer->execute(); #ifndef _USE_BASIC_SYNTHESIZER_ // Save/export results and data semiProcTexSynthesizer->saveResults(); #endif // Finalization // - clean/release resources semiProcTexSynthesizer->finalize(); delete semiProcTexSynthesizer; semiProcTexSynthesizer = nullptr; // Exit return 0; }
6,776
C++
.cpp
162
40.006173
141
0.575266
ASTex-ICube/semiproctex
39
8
2
LGPL-2.1
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,896
SptBasicSynthesizer.cpp
ASTex-ICube_semiproctex/Semiproc_synthesis_Src/SptSynthesizer/SptBasicSynthesizer.cpp
/* * Publication: Semi-Procedural Textures Using Point Process Texture Basis Functions * Computer Graphics Forum (EGSR 2020 special issue) * Authors: P. Guehl , R. AllEgre , J.-M. Dischler, B. Benes , and E. Galin * * Code author: Pascal Guehl */ /** * @version 1.0 */ #include "SptBasicSynthesizer.h" /****************************************************************************** ******************************* INCLUDE SECTION ****************************** ******************************************************************************/ // Project #include "SptBasicHviewInterface.h" // System #include <cassert> // STL #include <iostream> #include <algorithm> #include <functional> #include <numeric> #include <fstream> #include <sstream> /****************************************************************************** ****************************** NAMESPACE SECTION ***************************** ******************************************************************************/ // Project using namespace Spt; /****************************************************************************** ************************* DEFINE AND CONSTANT SECTION ************************ ******************************************************************************/ /****************************************************************************** ***************************** TYPE DEFINITION ******************************** ******************************************************************************/ /****************************************************************************** ***************************** METHOD DEFINITION ****************************** ******************************************************************************/ /****************************************************************************** * Constructor ******************************************************************************/ SptBasicSynthesizer::SptBasicSynthesizer() : mHviewInterface( nullptr ) //, GUIDE( 0.f ) //, STRENGTH( 0.f ) //, INITLEVEL( 0 ) //, BLOCSIZE( 0 ) //, INITERR( 0.f ) //, INDEXWEIGHT( 0.f ) { // Hview interface mHviewInterface = new SptBasicHviewInterface; } /****************************************************************************** * Destructor ******************************************************************************/ SptBasicSynthesizer::~SptBasicSynthesizer() { // Hview interface delete mHviewInterface; mHviewInterface = nullptr; } /****************************************************************************** * Initialize ******************************************************************************/ void SptBasicSynthesizer::initialize() { // Hview interface mHviewInterface->initialize(); } /****************************************************************************** * Finalize ******************************************************************************/ void SptBasicSynthesizer::finalize() { // Hview interface mHviewInterface->finalize(); } /****************************************************************************** * Launch the synthesis pipeline ******************************************************************************/ void SptBasicSynthesizer::execute() { // Delegate synthesis to hview interface mHviewInterface->execute(); } /****************************************************************************** * Save/export synthesis results ******************************************************************************/ void SptBasicSynthesizer::saveResults() { } /****************************************************************************** * Semi-procedural texture synthesis parameters ******************************************************************************/ void SptBasicSynthesizer::setExemplarName( const char* pText ) { // Hview interface mHviewInterface->setExemplarName( pText ); } /****************************************************************************** * Semi-procedural texture synthesis parameters ******************************************************************************/ void SptBasicSynthesizer::setGUIDE( const float pValue ) { // Hview interface mHviewInterface->setGUIDE( pValue ); } /****************************************************************************** * Semi-procedural texture synthesis parameters ******************************************************************************/ void SptBasicSynthesizer::setSTRENGTH( const float pValue ) { // Hview interface mHviewInterface->setSTRENGTH( pValue ); } /****************************************************************************** * Semi-procedural texture synthesis parameters ******************************************************************************/ void SptBasicSynthesizer::setINITLEVEL( const int pValue ) { // Hview interface mHviewInterface->setINITLEVEL( pValue ); } /****************************************************************************** * Semi-procedural texture synthesis parameters ******************************************************************************/ void SptBasicSynthesizer::setBLOCSIZE( const int pValue ) { // Hview interface mHviewInterface->setBLOCSIZE( pValue ); } /****************************************************************************** * Semi-procedural texture synthesis parameters ******************************************************************************/ void SptBasicSynthesizer::setINITERR( const float pValue ) { // Hview interface mHviewInterface->setINITERR( pValue ); } /****************************************************************************** * Semi-procedural texture synthesis parameters ******************************************************************************/ void SptBasicSynthesizer::setINDEXWEIGHT( const float pValue ) { // Hview interface mHviewInterface->setINDEXWEIGHT( pValue ); }
5,937
C++
.cpp
149
38.208054
84
0.354503
ASTex-ICube/semiproctex
39
8
2
LGPL-2.1
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,897
SptSynthesizer.cpp
ASTex-ICube_semiproctex/Semiproc_synthesis_Src/SptSynthesizer/SptSynthesizer.cpp
/* * Publication: Semi-Procedural Textures Using Point Process Texture Basis Functions * Computer Graphics Forum (EGSR 2020 special issue) * Authors: P. Guehl , R. AllEgre , J.-M. Dischler, B. Benes , and E. Galin * * Code author: Pascal Guehl */ /** * @version 1.0 */ #include "SptSynthesizer.h" /****************************************************************************** ******************************* INCLUDE SECTION ****************************** ******************************************************************************/ // Project #include "SptHviewInterface.h" // System #include <cassert> // STL #include <iostream> #include <algorithm> #include <functional> #include <numeric> #include <fstream> #include <sstream> /****************************************************************************** ****************************** NAMESPACE SECTION ***************************** ******************************************************************************/ // Project using namespace Spt; /****************************************************************************** ************************* DEFINE AND CONSTANT SECTION ************************ ******************************************************************************/ /****************************************************************************** ***************************** TYPE DEFINITION ******************************** ******************************************************************************/ /****************************************************************************** ***************************** METHOD DEFINITION ****************************** ******************************************************************************/ /****************************************************************************** * Constructor ******************************************************************************/ SptSynthesizer::SptSynthesizer() : mHviewInterface( nullptr ) // - exemplar , mExemplarName() , mExemplarWidth( 0 ) , mExemplarHeight( 0 ) // - output , mOutputWidth( 0 ) , mOutputHeight( 0 ) // - pyramid , mPyramidNbMipmapLevels( 0 ) , mPyramidMaxLevel( 0 ) , mPyramidMinSize( 0 ) , mPyramidNbLevels( 0 ) // - block initialization , mblockInitGridWidth( 0 ) , mblockInitGridHeight( 0 ) , mblockInitBlockWidth( 0 ) , mblockInitBlockHeight( 0 ) , mblockInitUseSmartInitialization( false ) , mblockInitSmartInitNbPasses( 0 ) // - correction pass , mCorrectionNbPasses( 0 ) , mCorrectionSubPassBlockSize( 0 ) , mCorrectionNeighborhoodSize( 0 ) , mCorrectionNeighborSearchRadius( 0 ) , mCorrectionNeighborSearchNbSamples( 0 ) , mCorrectionNeighborSearchDepth( 0 ) // - material , mCorrectionWeightAlbedo( 1.f ) , mCorrectionWeightHeight( 1.f ) , mCorrectionWeightNormal( 1.f ) , mCorrectionWeightRoughness( 1.f ) // - label map , mUseLabelMap( false ) , mLabelmapType( 0 ) , mUseLabelSampler( false ) , mLabelSamplerAreaThreshold( 0.f ) // - guidance , mCorrectionGuidanceWeight( 0.f ) , mCorrectionExemplarWeightDistance( 0.f ) , mCorrectionGuidanceWeightDistance( 0.f ) , mCorrectionLabelErrorAmount( 0.f ) // - semi-procedural , mSemiProcTexPPTBFThreshold( 0.f ) , mSemiProcTexRelaxContraintMin( 0.f ) , mSemiProcTexRelaxContraintMax( 0.f ) , mSemiProcTexGuidanceWeight( 0.f ) , mSemiProcTexDistancePower( 0.f ) , mSemiProcTexInitializationError( 0.f ) , mSemiProcTexNbLabels( 1 ) // [PPTBF] , mPptbfShiftX( 0 ) , mPptbfShiftY( 0 ) { // Hview interface mHviewInterface = new SptHviewInterface; } /****************************************************************************** * Destructor ******************************************************************************/ SptSynthesizer::~SptSynthesizer() { // Hview interface delete mHviewInterface; mHviewInterface = nullptr; } /****************************************************************************** * Initialize ******************************************************************************/ void SptSynthesizer::initialize() { // Hview interface mHviewInterface->initialize(); } /****************************************************************************** * Finalize ******************************************************************************/ void SptSynthesizer::finalize() { // Hview interface mHviewInterface->finalize(); } /****************************************************************************** * Load synthesis parameters * * @param pFilename * * @return error status ******************************************************************************/ int SptSynthesizer::loadParameters( const char* pFilename ) { //------------------------------------------------------------------------- // Analyse name to extract data info // - filename const std::string filename = std::string( pFilename ); // - image directory const size_t directoryIndex = filename.find_last_of( "/\\" ); const std::string imageDirectory = filename.substr( 0, directoryIndex ); // - file extension const size_t extensionIndex = filename.find_last_of( "." ); const std::string imageExtension = filename.substr( extensionIndex + 1 ); // - image name std::string imageName = filename.substr( directoryIndex + 1 ); const size_t nameIndex = imageName.find_last_of( "." ); const std::string imageSuffix = "_scrop"; imageName = imageName.substr( 0, nameIndex - imageSuffix.size() ); //------------------------------------------------------------------------- // Load synthesis parameter file std::string synthesisParameterFilename = ""; { // - filename const std::string filename = std::string( pFilename ); // - image directory const size_t directoryIndex = filename.find_last_of( "/\\" ); const std::string imageDirectory = filename.substr( 0, directoryIndex ); // - file extension const size_t extensionIndex = filename.find_last_of( "." ); const std::string imageExtension = filename.substr( extensionIndex + 1 ); // - image name std::string imageName = filename.substr( directoryIndex + 1 ); const size_t nameIndex = imageName.find_last_of( "." ); const std::string imageSuffix = "_scrop"; imageName = imageName.substr( 0, nameIndex - imageSuffix.size() ); // Load segmented file (structure map) const std::string synthesisParameterFileSuffix = "_scrop_synthesis_params.txt"; synthesisParameterFilename = imageDirectory + std::string( "/" ) + imageName + synthesisParameterFileSuffix; } //------------------------------------------------------------------------- // Open file std::ifstream semiProcTexConfigFile; //std::string semiProcTexConfigFilename = std::string( pFilename ); std::string semiProcTexConfigFilename = synthesisParameterFilename; semiProcTexConfigFile.open( semiProcTexConfigFilename ); if ( ! semiProcTexConfigFile.is_open() ) { // Log info std::cout << "ERROR: file cannot be opened: " << std::string( semiProcTexConfigFilename ) << std::endl; // Handle error assert( false ); return -1; } // Temp variables std::string lineData; std::string text; //---------------------------------------------- // [EXEMPLAR] //---------------------------------------------- std::getline( semiProcTexConfigFile, lineData ); // - name std::getline( semiProcTexConfigFile, lineData ); { std::stringstream ss( lineData ); ss >> text; ss >> mExemplarName; } // - exemplarSize std::getline( semiProcTexConfigFile, lineData ); { std::stringstream ss( lineData ); ss >> text; ss >> mExemplarWidth; ss >> mExemplarHeight; } //---------------------------------------------- // [SYNTHESIS] //---------------------------------------------- std::getline( semiProcTexConfigFile, lineData ); // - outputSize std::getline( semiProcTexConfigFile, lineData ); { std::stringstream ss( lineData ); ss >> text; ss >> mOutputWidth; ss >> mOutputHeight; } //---------------------------------------------- // [PYRAMID] //---------------------------------------------- std::getline( semiProcTexConfigFile, lineData ); // - nbMipmapLevels std::getline( semiProcTexConfigFile, lineData ); { std::stringstream ss( lineData ); ss >> text; ss >> mPyramidNbMipmapLevels; } // - pyramidMaxLevel std::getline( semiProcTexConfigFile, lineData ); { std::stringstream ss( lineData ); ss >> text; ss >> mPyramidMaxLevel; } // - pyramidMinSize std::getline( semiProcTexConfigFile, lineData ); { std::stringstream ss( lineData ); ss >> text; ss >> mPyramidMinSize; } // - nbPyramidLevels std::getline( semiProcTexConfigFile, lineData ); { std::stringstream ss( lineData ); ss >> text; ss >> mPyramidNbLevels; } //---------------------------------------------- // [BLOCK INITIALIZATION] //---------------------------------------------- std::getline( semiProcTexConfigFile, lineData ); // - blockGrid std::getline( semiProcTexConfigFile, lineData ); { std::stringstream ss( lineData ); ss >> text; ss >> mblockInitGridWidth; ss >> mblockInitGridHeight; } // - blockSize std::getline( semiProcTexConfigFile, lineData ); { std::stringstream ss( lineData ); ss >> text; ss >> mblockInitBlockWidth; ss >> mblockInitBlockHeight; } // - useSmartInitialization std::getline( semiProcTexConfigFile, lineData ); { std::stringstream ss( lineData ); ss >> text; int value; ss >> value; mblockInitUseSmartInitialization = value > 0 ? true : false; } // - smartInitNbPasses std::getline( semiProcTexConfigFile, lineData ); { std::stringstream ss( lineData ); ss >> text; ss >> mblockInitSmartInitNbPasses; } //---------------------------------------------- // [CORRECTION PASS] //---------------------------------------------- std::getline( semiProcTexConfigFile, lineData ); // - correctionNbPasses std::getline( semiProcTexConfigFile, lineData ); { std::stringstream ss( lineData ); ss >> text; ss >> mCorrectionNbPasses; } // - correctionSubPassBlockSize std::getline( semiProcTexConfigFile, lineData ); { std::stringstream ss( lineData ); ss >> text; ss >> mCorrectionSubPassBlockSize; } // - correctionNeighborhoodSize std::getline( semiProcTexConfigFile, lineData ); { std::stringstream ss( lineData ); ss >> text; ss >> mCorrectionNeighborhoodSize; } // - correctionNeighborSearchRadius std::getline( semiProcTexConfigFile, lineData ); { std::stringstream ss( lineData ); ss >> text; ss >> mCorrectionNeighborSearchRadius; } // - correctionNeighborSearchNbSamples std::getline( semiProcTexConfigFile, lineData ); { std::stringstream ss( lineData ); ss >> text; ss >> mCorrectionNeighborSearchNbSamples; } // - correctionNeighborSearchDepth std::getline( semiProcTexConfigFile, lineData ); { std::stringstream ss( lineData ); ss >> text; ss >> mCorrectionNeighborSearchDepth; } //---------------------------------------------- // [MATERIAL] //---------------------------------------------- std::getline( semiProcTexConfigFile, lineData ); // - correctionWeightAlbedo std::getline( semiProcTexConfigFile, lineData ); { std::stringstream ss( lineData ); ss >> text; ss >> mCorrectionWeightAlbedo; } // - correctionWeightHeight std::getline( semiProcTexConfigFile, lineData ); { std::stringstream ss( lineData ); ss >> text; ss >> mCorrectionWeightHeight; } // - correctionWeightNormal std::getline( semiProcTexConfigFile, lineData ); { std::stringstream ss( lineData ); ss >> text; ss >> mCorrectionWeightNormal; } // - correctionWeightRoughness std::getline( semiProcTexConfigFile, lineData ); { std::stringstream ss( lineData ); ss >> text; ss >> mCorrectionWeightRoughness; } //---------------------------------------------- // [LABEL MAP] //---------------------------------------------- std::getline( semiProcTexConfigFile, lineData ); // - useLabelMap std::getline( semiProcTexConfigFile, lineData ); { std::stringstream ss( lineData ); ss >> text; int value; ss >> value; mUseLabelMap = value > 0 ? true : false; } // - labelmapType std::getline( semiProcTexConfigFile, lineData ); { std::stringstream ss( lineData ); ss >> text; ss >> mLabelmapType; } // - useLabelSampler std::getline( semiProcTexConfigFile, lineData ); { std::stringstream ss( lineData ); ss >> text; int value; ss >> value; mUseLabelSampler = value > 0 ? true : false; } // - labelSamplerAreaThreshold std::getline( semiProcTexConfigFile, lineData ); { std::stringstream ss( lineData ); ss >> text; ss >> mLabelSamplerAreaThreshold; } //---------------------------------------------- // [GUIDANCE] //---------------------------------------------- std::getline( semiProcTexConfigFile, lineData ); // - correctionGuidanceWeight std::getline( semiProcTexConfigFile, lineData ); { std::stringstream ss( lineData ); ss >> text; ss >> mCorrectionGuidanceWeight; } // - correctionExemplarWeightDistance std::getline( semiProcTexConfigFile, lineData ); { std::stringstream ss( lineData ); ss >> text; ss >> mCorrectionExemplarWeightDistance; } // - correctionGuidanceWeightDistance std::getline( semiProcTexConfigFile, lineData ); { std::stringstream ss( lineData ); ss >> text; ss >> mCorrectionGuidanceWeightDistance; } // - correctionLabelErrorAmount std::getline( semiProcTexConfigFile, lineData ); { std::stringstream ss( lineData ); ss >> text; ss >> mCorrectionLabelErrorAmount; } //---------------------------------------------- // [SEMI PROCEDURAL] //---------------------------------------------- std::getline( semiProcTexConfigFile, lineData ); // - PPTBFThreshold std::getline( semiProcTexConfigFile, lineData ); { std::stringstream ss( lineData ); ss >> text; ss >> mSemiProcTexPPTBFThreshold; } // - relaxContraints std::getline( semiProcTexConfigFile, lineData ); { std::stringstream ss( lineData ); ss >> text; ss >> mSemiProcTexRelaxContraintMin; ss >> mSemiProcTexRelaxContraintMax; } // - guidanceWeight std::getline( semiProcTexConfigFile, lineData ); { std::stringstream ss( lineData ); ss >> text; ss >> mSemiProcTexGuidanceWeight; } // - distancePower std::getline( semiProcTexConfigFile, lineData ); { std::stringstream ss( lineData ); ss >> text; ss >> mSemiProcTexDistancePower; } // - initializationError std::getline( semiProcTexConfigFile, lineData ); { std::stringstream ss( lineData ); ss >> text; ss >> mSemiProcTexInitializationError; } // - nbLabels std::getline( semiProcTexConfigFile, lineData ); { std::stringstream ss( lineData ); ss >> text; ss >> mSemiProcTexNbLabels; } //---------------------------------------------- // [PPTBF] //---------------------------------------------- std::getline( semiProcTexConfigFile, lineData ); // - shift std::getline( semiProcTexConfigFile, lineData ); { std::stringstream ss( lineData ); ss >> text; ss >> mPptbfShiftX; ss >> mPptbfShiftY; } // Close file semiProcTexConfigFile.close(); //-------------------------------------- // TODO: adapt semi-procedural texture synthesis parameters to hview api ones //-------------------------------------- // TODO // ... //-------------------------------------- // TODO: load exemplar data //-------------------------------------- // Load exemplar data // - color const std::string exemplarFilename = imageDirectory + std::string( "/" ) + imageName + std::string( "_scrop" ) + std::string( ".png" ); loadExemplar( exemplarFilename.c_str() ); // - structure const std::string exemplarStructureFilename = imageDirectory + std::string( "/" ) + imageName + std::string( "_seg" ) + std::string( "_scrop" ) + std::string( ".png" ); loadExemplarStructureMap( exemplarStructureFilename.c_str() ); // - distance const std::string exemplarDistanceFilename = imageDirectory + std::string( "/" ) + imageName + std::string( "_distance" ) + std::string( "_scrop" ) + std::string( ".png" ); loadExemplarDistanceMap( exemplarDistanceFilename.c_str() ); // - labels (TODO: change this naming convention with _label_scrop?) const std::string exemplarLabelFilename = imageDirectory + std::string( "/" ) + imageName + std::string( "_featcol_class" ) + std::string( ".png" ); loadExemplarLabelMap( exemplarLabelFilename.c_str() ); //-------------------------------------- // TODO: load guidance data //-------------------------------------- // Load guidance data // - PPTBF const std::string guidancePPTBFFilename = imageDirectory + std::string( "/" ) + imageName + std::string( "_pptbf" ) + std::string( "_guidance" ) + std::string( ".png" ); loadGuidancePPTBF( guidancePPTBFFilename.c_str() ); // - mask const std::string guidanceMaskFilename = imageDirectory + std::string( "/" ) + imageName + std::string( "_mask" ) + std::string( "_guidance" ) + std::string( ".png" ); loadGuidanceMask( guidanceMaskFilename.c_str() ); // - distance const std::string guidanceDistanceFilename = imageDirectory + std::string( "/" ) + imageName + std::string( "_distance" ) + std::string( "_guidance" ) + std::string( ".png" ); loadGuidanceDistanceMap( guidanceDistanceFilename.c_str() ); // - labels const std::string guidanceLabelFilename = imageDirectory + std::string( "/" ) + imageName + std::string( "_label" ) + std::string( "_guidance" ) + std::string( ".png" ); loadGuidanceLabelMap( guidanceLabelFilename.c_str() ); // Exit code return 0; } /****************************************************************************** * Launch the synthesis pipeline ******************************************************************************/ void SptSynthesizer::execute() { // Delegate synthesis to hview interface mHviewInterface->execute(); } /****************************************************************************** * Save/export synthesis results ******************************************************************************/ void SptSynthesizer::saveResults() { } /****************************************************************************** * Initialization stage * - strategies/policies to choose blocks at initialization ******************************************************************************/ void SptSynthesizer::smartInitialization() { } /****************************************************************************** * Correction pass ******************************************************************************/ void SptSynthesizer::correction() { } /****************************************************************************** * Upsampling pass ******************************************************************************/ void SptSynthesizer::upsampling() { } /****************************************************************************** * Load exemplar (color texture) * * @param pFilename ******************************************************************************/ void SptSynthesizer::loadExemplar(const char* pFilename) { // Delegate to hview interface mHviewInterface->loadExemplar( pFilename ); } /****************************************************************************** * Load structure map (binary) * * @param pFilename ******************************************************************************/ void SptSynthesizer::loadExemplarStructureMap( const char* pFilename ) { // Delegate to hview interface mHviewInterface->loadExemplarStructureMap( pFilename ); } /****************************************************************************** * Load distance map * * @param pFilename ******************************************************************************/ void SptSynthesizer::loadExemplarDistanceMap( const char* pFilename ) { // Delegate to hview interface mHviewInterface->loadExemplarDistanceMap( pFilename ); } /****************************************************************************** * Load label map * * @param pFilename ******************************************************************************/ void SptSynthesizer::loadExemplarLabelMap( const char* pFilename ) { // Delegate to hview interface mHviewInterface->loadExemplarLabelMap( pFilename ); } /****************************************************************************** * Load guidance PPTBF * * @param pFilename ******************************************************************************/ void SptSynthesizer::loadGuidancePPTBF( const char* pFilename ) { // Delegate to hview interface mHviewInterface->loadGuidancePPTBF( pFilename ); } /****************************************************************************** * Load guidance mask * * @param pFilename ******************************************************************************/ void SptSynthesizer::loadGuidanceMask( const char* pFilename ) { // Delegate to hview interface mHviewInterface->loadGuidanceMask( pFilename) ; } /****************************************************************************** * Load guidance distance map * * @param pFilename ******************************************************************************/ void SptSynthesizer::loadGuidanceDistanceMap( const char* pFilename ) { // Delegate to hview interface mHviewInterface->loadGuidanceDistanceMap( pFilename ); } /****************************************************************************** * Load guidance label map * * @param pFilename ******************************************************************************/ void SptSynthesizer::loadGuidanceLabelMap( const char* pFilename ) { // Delegate to hview interface mHviewInterface->loadGuidanceLabelMap( pFilename ); }
21,684
C++
.cpp
646
31.399381
176
0.545637
ASTex-ICube/semiproctex
39
8
2
LGPL-2.1
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,898
SptBasicHviewInterface.cpp
ASTex-ICube_semiproctex/Semiproc_synthesis_Src/SptSynthesizer/SptBasicHviewInterface.cpp
/* * Publication: Semi-Procedural Textures Using Point Process Texture Basis Functions * Computer Graphics Forum (EGSR 2020 special issue) * Authors: P. Guehl , R. AllEgre , J.-M. Dischler, B. Benes , and E. Galin * * Code author: Pascal Guehl */ /** * @version 1.0 */ #include "SptBasicHviewInterface.h" /****************************************************************************** ******************************* INCLUDE SECTION ****************************** ******************************************************************************/ // Project #include "SptImageHelper.h" // System #include <cassert> // STL #include <iostream> #include <algorithm> #include <functional> #include <numeric> #include <fstream> #include <sstream> // hview #ifndef M_PI #define M_PI 3.14159265358979323846 #endif #include <hvVec2.h> #include <hvArray2.h> #include <hvBitmap.h> #include <hvPictRGB.h> #include "hvPicture.h" /****************************************************************************** ****************************** NAMESPACE SECTION ***************************** ******************************************************************************/ // Project using namespace Spt; /****************************************************************************** ************************* DEFINE AND CONSTANT SECTION ************************ ******************************************************************************/ /** * OUTPUT SIZE */ const int SS = 400; const int NPPTBFS = 1; const int MAXPPTBF = 10; int pptbfid = 0; int di = 1; // for transition, next pptbf is pptbfid + di std::string pptbfParameters[NPPTBFS]; char *pptbf_param[NPPTBFS] = { "0 0.91 75 0 3 0 0 1 1 8 0.9 2 0 1 0.7 1 2 0 0 5 5 1 0.2 2 0 0.1 0.2 0" }; const bool TRANSITION = false; const float threshtransition = 1.0; // 1.0 = keep same tresh const int SPOSX = 0; const int SPOSY = 0; //float ZZ = 1.0; /*const */int PSIZE = 512; /*const*/ int STARTX = 10 * PSIZE; /*const*/ int STARTY = 10 * PSIZE; int shiftx = STARTX + SPOSX * PSIZE + 0 * PSIZE, shifty = STARTY + SPOSY * PSIZE; float featpercent[10]; const int npptbf = 1; char* name[npptbf] = { "cracked_asphalt_160796" }; int do_tiling[NPPTBFS]; float jittering[MAXPPTBF]; int resolution[MAXPPTBF]; float rotation[MAXPPTBF]; float rescalex[MAXPPTBF]; float turbAmp[MAXPPTBF][3]; int windowShape[MAXPPTBF]; float windowArity[MAXPPTBF]; float windowLarp[MAXPPTBF]; float windowNorm[MAXPPTBF]; float windowSmoothness[MAXPPTBF]; float windowBlend[MAXPPTBF]; float windowSigwcell[MAXPPTBF]; int featureBombing[MAXPPTBF]; float featureNorm[MAXPPTBF]; float featureWinfeatcorrel[MAXPPTBF]; float featureAniso[MAXPPTBF]; int featureMinNbKernels[MAXPPTBF], featureMaxNbKernels[MAXPPTBF]; float featureSigcos[MAXPPTBF]; float featureSigcosvar[MAXPPTBF]; int featureFrequency[MAXPPTBF]; float featurePhaseShift[MAXPPTBF]; float featureThickness[MAXPPTBF]; float featureCurvature[MAXPPTBF]; float featureOrientation[MAXPPTBF]; /****************************************************************************** ***************************** TYPE DEFINITION ******************************** ******************************************************************************/ /****************************************************************************** ***************************** METHOD DEFINITION ****************************** ******************************************************************************/ namespace hview { class hvPictureMetrics { public: static void histogramm(hview::hvPict<float> &pp, float *histo, int bins, float vmin, float vmax) { int i, j; for (i = 0; i < bins; i++) histo[i] = 0.0f; for (j = 0; j < pp.sizeY(); j++) for (i = 0; i < pp.sizeX(); i++) { int iv = (int)((float)(bins)*(pp.get(i, j) - vmin) / (vmax - vmin)); if (iv >= bins) iv = bins - 1; histo[iv] += 1.0f / (float)(pp.sizeX()*pp.sizeY()); } } static float computeThresh(float percent, float *histo, int bins, float vmin, float vmax) { int i; float sum = 0.0; for (i = 0; i < bins && sum < percent; i++) sum += histo[i]; if (i == bins) return vmax; float ratio = (percent - (sum - histo[i])) / histo[i]; //float ratio = 0.5f; //printf("compute Thresh bin =%d, sum=%g, percent=%g\n", i, sum, percent); return vmin + (vmax - vmin)*((float)(i - 1) / (float)bins + ratio / (float)bins); } }; } /****************************************************************************** * PPTBF synthesis * * @param pixelzoom * @param pptbfpi * @param ppval ******************************************************************************/ void SptBasicHviewInterface::pptbfshader( float pixelzoom, hview::hvPict< float >& pptbfpi, hview::hvPict< float >& ppval ) { #ifndef USE_MULTITHREADED_PPTBF int i, j; #else float pointvalue, cellpointx, cellpointy; float pointvalue2, cellpointx2, cellpointy2; #endif for (int ipara = 0; ipara < NPPTBFS; ipara++) { #if 0 sscanf(pptbf_param[ipara], "%d %g %d %g %g %g %g %g %d %g %g %g %g %g %g %d %g %g %g %d %d %g %g %d %g %g %g %g\n", &do_tiling[ipara], &jittering[ipara], &resolution[ipara], &rotation[ipara], &rescalex[ipara], &turbAmp[ipara][0], &turbAmp[ipara][1], &turbAmp[ipara][2], &windowShape[ipara], &windowArity[ipara], &windowLarp[ipara], &windowNorm[ipara], &windowSmoothness[ipara], &windowBlend[ipara], &windowSigwcell[ipara], &featureBombing[ipara], &featureNorm[ipara], &featureWinfeatcorrel[ipara], &featureAniso[ipara], &featureMinNbKernels[ipara], &featureMaxNbKernels[ipara], &featureSigcos[ipara], &featureSigcosvar[ipara], &featureFrequency[ipara], &featurePhaseShift[ipara], &featureThickness[ipara], &featureCurvature[ipara], &featureOrientation[ipara]); #else sscanf(pptbfParameters[ipara].c_str(), "%d %g %d %g %g %g %g %g %d %g %g %g %g %g %g %d %g %g %g %d %d %g %g %d %g %g %g %g\n", &do_tiling[ipara], &jittering[ipara], &resolution[ipara], &rotation[ipara], &rescalex[ipara], &turbAmp[ipara][0], &turbAmp[ipara][1], &turbAmp[ipara][2], &windowShape[ipara], &windowArity[ipara], &windowLarp[ipara], &windowNorm[ipara], &windowSmoothness[ipara], &windowBlend[ipara], &windowSigwcell[ipara], &featureBombing[ipara], &featureNorm[ipara], &featureWinfeatcorrel[ipara], &featureAniso[ipara], &featureMinNbKernels[ipara], &featureMaxNbKernels[ipara], &featureSigcos[ipara], &featureSigcosvar[ipara], &featureFrequency[ipara], &featurePhaseShift[ipara], &featureThickness[ipara], &featureCurvature[ipara], &featureOrientation[ipara]); #endif } //for (int ipara = 0; ipara<NPPTBFS; ipara++) turbAmp[ipara][0] *= 2.0; //hvPictRGB<unsigned char> testImage(pptbfpi.sizeX(), example[pptbfid].sizeY(), hvColRGB<unsigned char>(0)); #ifdef USE_MULTITHREADED_PPTBF const int nbPixels = pptbfpi.sizeX() * pptbfpi.sizeY(); PtThreadPool.AppendTask([&](const MyThreadPool::ThreadData* thread) { int beg = thread->id * pptbfpi.sizeY() / thread->nThreads; int end = (thread->id + 1) * pptbfpi.sizeY() / thread->nThreads; end = std::min(end, pptbfpi.sizeY()); for (int j = beg; j < end; ++j) for (int i = 0; i < pptbfpi.sizeX(); ++i) //for ( int k = thread->id; k < nbPixels; k += thread->nThreads ) #else //#pragma omp parallel for (i = 0; i < pptbfpi.sizeX(); i++) for (j = 0; j < pptbfpi.sizeY(); j++) #endif { #ifdef USE_MULTITHREADED_PPTBF //int i = k % pptbfpi.sizeX(); //int j = k / pptbfpi.sizeX(); //std::cout << "thread->id: " << thread->id << " (" << i << "," << j << ")" << std::endl; #endif float pointvalue, cellpointx, cellpointy; float pointvalue2, cellpointx2, cellpointy2; float x = ((float)i*pixelzoom + (float)(shiftx - padding)) / (float)SS + 10.0; float y = ((float)j*pixelzoom + (float)(shifty - padding)) / (float)SS + 10.0; float zoom = 0.0; float pptbfvv = 0.f; float transition = (float)i / (float)pptbfpi.sizeX(); // +0.3*(1.0 - 2.5*hvNoise::turbulence((double)x*2.0, (double)y*2.0, 1.24, 0.0001)); if (transition < 0.25) transition = 0.0; else if (transition < 0.75) transition = (transition - 0.25) / 0.5; else transition = 1.0; if (!TRANSITION) { int qq = pptbfid; zoom = (float)SS / (float)resolution[qq]; //windowBlend[qq] = transition; //if (j > 200) windowLarp[qq] = 0.0; //else windowLarp[qq] = 0.5-0.5*(float)j / 200.0; //windowSmoothness[qq] = 1.5; //if (i >= pptbfpi.sizeX() - 100) windowSmoothness[qq] -= 0.5*(float)(i - pptbfpi.sizeX() + 100) / 100.0; pptbfvv = hview::hvNoise::cpptbf_gen_v2c(x, y, zoom, rotation[qq] * M_PI, rescalex[qq], turbAmp[qq], do_tiling[qq], jittering[qq], windowShape[qq], windowArity[qq], windowLarp[qq], windowSmoothness[qq], windowNorm[qq], windowBlend[qq], windowSigwcell[qq], featureBombing[qq], featureNorm[qq], featureWinfeatcorrel[qq], featureAniso[qq], featureMinNbKernels[qq], featureMaxNbKernels[qq], featureSigcos[qq], featureSigcosvar[qq], featureFrequency[qq], featurePhaseShift[qq] * M_PI*0.5, featureThickness[qq], featureCurvature[qq], featureOrientation[qq] * M_PI, pointvalue, cellpointx, cellpointy ); //pptbfvv = 1.0 - pptbfvv; //pptbfvv = 1.0 - pptbfvv; //int subid = pptbfid+1; //float scx = 1.0, scy = 1.0; //if (pptbfvv >= 0.0) //thresh[pptbfid]) //{ // zoom = (float)SS / (float)resolution[subid]; // float pptbfvvsub = hvNoise::cpptbf_gen_v2(x*scx, y*scy, //cellpointx*100.0 + x*scx, cellpointy*100.0 + y*scy, // zoom, rotation[subid], rescalex[subid], turbAmp[subid], // do_tiling[subid], jittering[subid], // windowShape[subid], windowArity[subid], windowLarp[subid], windowSmoothness[subid], windowNorm[subid], windowBlend[subid], windowSigwcell[subid], // featureBombing[subid], featureNorm[subid], featureWinfeatcorrel[subid], featureAniso[subid], // featureMinNbKernels[subid], featureMaxNbKernels[subid], featureSigcos[subid], featureSigcosvar[subid], // featureFrequency[subid], featurePhaseShift[subid], featureThickness[subid], featureCurvature[subid], featureOrientation[subid] // ); // //pptbfvv = pptbfvvsub; // pptbfvv = pow(pptbfvv < pptbfvvsub ? pptbfvv : pptbfvvsub, 0.5); // //pptbfvv = pow(pptbfvvsub, 1.0); //} } else { // Not provided in this version... assert( false ); } if (!std::isnan(pptbfvv) && !std::isinf(pptbfvv)) { // Write data // - pptbf pptbfpi.update(i, j, pptbfvv); // - random value ppval.update(i, j, pointvalue); } else { printf("\nPPTBF: nan or inf..."); } } #ifdef USE_MULTITHREADED_PPTBF }); // multi-thread #endif } /****************************************************************************** * Constructor ******************************************************************************/ SptBasicHviewInterface::SptBasicHviewInterface() : mExemplarName() , GUIDE( 0.f ) , STRENGTH( 0.f ) , INITLEVEL( 0 ) , BLOCSIZE( 0 ) , INITERR( 0.f ) , INDEXWEIGHT( 0.f ) , padding( 0 ) { } /****************************************************************************** * Destructor ******************************************************************************/ SptBasicHviewInterface::~SptBasicHviewInterface() { } /****************************************************************************** * Initialize ******************************************************************************/ void SptBasicHviewInterface::initialize() { } /****************************************************************************** * Finalize ******************************************************************************/ void SptBasicHviewInterface::finalize() { } /****************************************************************************** * Launch the synthesis pipeline ******************************************************************************/ void SptBasicHviewInterface::execute() { // TODO: // Put here, code of the basic software algorithm // ... /*const*/ int STOPATLEVEL = 0; //int labelmapType = std::stoi(pArgv[indexParameter++]); // default: 0: random, 1: classification int labelmapType = 0; const bool TRANSITION = false; const float threshtransition = 1.0; // 1.0 = keep same tresh const int SPOSX = 0; const int SPOSY = 0; float vvmin[10] = { 0.0 }; float vvmax[10] = { 1.0 }; char pname[ 500 ]; hview::hvPictRGB<unsigned char> example[NPPTBFS]; hview::hvPictRGB<unsigned char> exalbedo[NPPTBFS]; hview::hvBitmap exseg[NPPTBFS]; int i, j, k, ii, jj; // Update automatic padding padding = (1 << INITLEVEL) * BLOCSIZE; hview::hvColRGB<unsigned char> pptbf_col1[] = { hview::hvColRGB<unsigned char>(208,68,43),hview::hvColRGB<unsigned char>(208,68,43),hview::hvColRGB<unsigned char>(93,80,68), hview::hvColRGB<unsigned char>(200,150,130),hview::hvColRGB<unsigned char>(200,150,130), hview::hvColRGB<unsigned char>(113,174, 210),hview::hvColRGB<unsigned char>(113,174, 210), //hvColRGB<unsigned char>(177,157,133),hvColRGB<unsigned char>(177,157,133), hvColRGB<unsigned char>(208,208,208),hvColRGB<unsigned char>(208,208,208),hvColRGB<unsigned char>(200,126,113), hvColRGB<unsigned char>(200,126,113), hview::hvColRGB<unsigned char>(239,224,95),hview::hvColRGB<unsigned char>(239,224,195), hview::hvColRGB<unsigned char>(87,80,71),hview::hvColRGB<unsigned char>(87,80,71),hview::hvColRGB<unsigned char>(179, 129, 103), hview::hvColRGB<unsigned char>(179, 129, 103), hview::hvColRGB<unsigned char>(68,89,113), hview::hvColRGB<unsigned char>(68,89,113) }; hview::hvColRGB<unsigned char> pptbf_col2[] = { hview::hvColRGB<unsigned char>(108,38,23),hview::hvColRGB<unsigned char>(108,38,23), hview::hvColRGB<unsigned char>(208, 206, 202),hview::hvColRGB<unsigned char>(208, 206, 202), hview::hvColRGB<unsigned char>(90,80,70),hview::hvColRGB<unsigned char>(90,80,70), hview::hvColRGB<unsigned char>(154,104,80),hview::hvColRGB<unsigned char>(154,104,80), //hvColRGB<unsigned char>(85,74,64),hvColRGB<unsigned char>(85,74,64), hvColRGB<unsigned char>(63,63,65),hvColRGB<unsigned char>(63,63,65),hvColRGB<unsigned char>(70,55,55), hvColRGB<unsigned char>(70,50,55), hview::hvColRGB<unsigned char>(123,84,44),hview::hvColRGB<unsigned char>(123,84,44), hview::hvColRGB<unsigned char>(27,26,23),hview::hvColRGB<unsigned char>(27,26,23), hview::hvColRGB<unsigned char>(156,165,163), hview::hvColRGB<unsigned char>(156,165,163), hview::hvColRGB<unsigned char>(201,230,249), hview::hvColRGB<unsigned char>(201,230,249) }; k = 0; name[ 0 ] = const_cast< char* >( mExemplarName.c_str() ); sprintf( pname, "%s_scrop.png", name[ k ] ); // Read image int width = 0; int height = 0; int nrChannels = 0; const int desired_channels = 0; // TODO: handle this parameter! unsigned char* data = nullptr; SptImageHelper::loadImage( pname, width, height, nrChannels, data, desired_channels ); if ( data == nullptr ) { std::cout << "Failed to load image: " << pname << std::endl; assert( false ); //return 1; // TODO: handle this! } /////////////////////////////////////////////////////////////////////// assert( width == height ); //PSIZE = 2 * width; // we want 2 times the original size for our tests !! //--------------------------------------------------------------------------------- // PSIZE must be a multiple of BLOCSIZE //int deltaPSIZE = 0; //PSIZE += deltaPSIZE; { // mimic makepyr() method int s = 0; int f = 1; int w = width; int h = height; while ( s < INITLEVEL && w > 16 && h > 16 ) { // shrink size w /= 2; h /= 2; // update pyramid info s++; f *= 2; } // Handle error if ( w < 2 * BLOCSIZE ) { printf( "\nERROR: block size %d must be less or equal than %d", w / 2 ); assert( false ); } int outputSize = 2 * width; // we want 2 times the original size for our tests !! int exemplarBlockSize = f * BLOCSIZE; if ( width < exemplarBlockSize || height < exemplarBlockSize ) { int maxBlockSize = std::min( width, height ) / f; printf( "\ERROR: block size %d must be less or equal to %d", BLOCSIZE, maxBlockSize ); assert( false ); } int nbBlocks = outputSize / ( f * BLOCSIZE ) + ( ( outputSize % ( f * BLOCSIZE ) ) == 0 ? 0 : 1 ); PSIZE = nbBlocks * ( f * BLOCSIZE ); } //--------------------------------------------------------------------------------- STARTX = 10 * PSIZE; STARTY = 10 * PSIZE; shiftx = STARTX + SPOSX * PSIZE + 0 * PSIZE; shifty = STARTY + SPOSY * PSIZE; /////////////////////////////////////////////////////////////////////// exalbedo[k].reset(width, height, hview::hvColRGB<unsigned char>(0)); for (int ii = 0; ii < width; ii++) for (int jj = 0; jj < height; jj++) { exalbedo[k].update(ii, jj, hview::hvColRGB<unsigned char>(data[nrChannels * (ii + jj*width)], data[nrChannels * (ii + jj*width) + 1], data[nrChannels * (ii + jj*width) + 2])); } SptImageHelper::freeImage( data ); sprintf(pname, "%s_seg_scrop.png", name[k]); data = nullptr; SptImageHelper::loadImage( pname, width, height, nrChannels, data, desired_channels ); if (data == nullptr) { std::cout << "Failed to load image: " << pname << std::endl; assert(false); //return 1; } exseg[k].reset(width, height, false); for (int ii = 0; ii < width; ii++) for (int jj = 0; jj < height; jj++) { exseg[k].set(ii, jj, (int)data[nrChannels * (ii + jj*width)] > 128 ? true : false); } SptImageHelper::freeImage( data ); //////////////////////////////////////////////////////////////////////////////////////// sprintf(pname, "%s_seg_scrop_pptbf_params.txt", name[k]); std::ifstream estimatedParameterFile(pname); std::string lineData; // Get threshold float threshold; std::getline(estimatedParameterFile, lineData); std::stringstream ssthreshold(lineData); ssthreshold >> threshold; // Get PPTBF parameters std::getline(estimatedParameterFile, lineData); // Store data float thresh[2] = { 0.899284 }; #if 0 thresh[k] = threshold; #else thresh[k] = 0.9f * threshold; printf("\nBEWARE: use0.95*threshold to test thin space between cells !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); #endif pptbf_param[k] = const_cast<char*>(lineData.c_str()); pptbfParameters[k] = lineData; // LOG info std::cout << std::endl; std::cout << "--------------------------------------------------------" << std::endl; std::cout << "PPTBF" << std::endl; std::cout << "--------------------------------------------------------" << std::endl; std::cout << std::endl; // PPTBF parameters std::vector< float > pptbf; std::stringstream sspptbf(lineData); float value; while (sspptbf >> value) { // Fill parameters pptbf.push_back(value); } int h = 0; // Point Process std::cout << "[POINT PROCESS]" << std::endl; std::cout << "tiling type: " << pptbf[h++] << std::endl; std::cout << "jittering: " << pptbf[h++] << std::endl; // Transformation std::cout << std::endl; std::cout << "[TRANSFORMATION]" << std::endl; std::cout << "resolution: " << pptbf[h++] << std::endl; std::cout << "rotation: " << pptbf[h++] << std::endl; std::cout << "aspectRatio: " << pptbf[h++] << std::endl; // Turbulence std::cout << std::endl; std::cout << "[TURBULENCE]" << std::endl; std::cout << "base amplitude: " << pptbf[h++] << std::endl; std::cout << "gain: " << pptbf[h++] << std::endl; std::cout << "frequency: " << pptbf[h++] << std::endl; // Window Function std::cout << std::endl; std::cout << "[WINDOW FUNCTION]" << std::endl; std::cout << "shape: " << pptbf[h++] << std::endl; std::cout << "arity: " << pptbf[h++] << std::endl; std::cout << "larp: " << pptbf[h++] << std::endl; std::cout << "norm: " << pptbf[h++] << std::endl; std::cout << "smoothness: " << pptbf[h++] << std::endl; std::cout << "blend: " << pptbf[h++] << std::endl; std::cout << "decay: " << pptbf[h++] << std::endl; // Feature Function std::cout << std::endl; std::cout << "[FEATURE FUNCTION]" << std::endl; std::cout << "type: " << pptbf[h++] << std::endl; std::cout << "norm: " << pptbf[h++] << std::endl; std::cout << "window feature correlation: " << pptbf[h++] << std::endl; std::cout << "anisotropy: " << pptbf[h++] << std::endl; std::cout << "nb min kernels: " << pptbf[h++] << std::endl; std::cout << "nb max kernels: " << pptbf[h++] << std::endl; std::cout << "decay: " << pptbf[h++] << std::endl; std::cout << "decay delta: " << pptbf[h++] << std::endl; std::cout << "frequency: " << pptbf[h++] << std::endl; std::cout << "phase shift: " << pptbf[h++] << std::endl; std::cout << "thickness: " << pptbf[h++] << std::endl; std::cout << "curvature: " << pptbf[h++] << std::endl; std::cout << "orientation: " << pptbf[h++] << std::endl; ////////////////////////////////////////////////////////////////////////////////////////// //// CUSTOM PCTS-like synthesis parameters //sprintf( pname, "%s_synthesis_params.txt", name[ k ] ); //std::ifstream synthesisParameterFile( pname ); // //// Get threshold //std::string text; //synthesisParameterFile >> text; //synthesisParameterFile >> GUIDE; //synthesisParameterFile >> text; //synthesisParameterFile >> STRENGTH; //synthesisParameterFile >> text; //synthesisParameterFile >> INITLEVEL; //synthesisParameterFile >> text; //synthesisParameterFile >> BLOCSIZE; //// Update automatic padding //padding = ( 1 << INITLEVEL ) * BLOCSIZE; //synthesisParameterFile >> text; //synthesisParameterFile >> INITERR; //synthesisParameterFile >> text; //synthesisParameterFile >> INDEXWEIGHT; // Update automatic padding //padding = ( 1 << INITLEVEL ) * BLOCSIZE; // LOG info std::cout << std::endl; std::cout << "--------------------------------------------------------" << std::endl; std::cout << "CUSTOM PCTS-like synthesis parameters:" << std::endl; std::cout << "--------------------------------------------------------\n" << std::endl; std::cout << "- GUIDE = " << GUIDE << std::endl; std::cout << "- STRENGTH = " << STRENGTH << std::endl; std::cout << "- INITLEVEL = " << INITLEVEL << std::endl; std::cout << "- BLOCSIZE = " << BLOCSIZE << std::endl; std::cout << "- INITERR = " << INITERR << std::endl; std::cout << "- INDEXWEIGHT = " << INDEXWEIGHT << std::endl; std::cout << "- labelmapType = " << labelmapType << std::endl; std::cout << std::endl; //////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////// // SAVE CUSTOM PCTS-like synthesis parameters sprintf(pname, "%s_synthesis_params.txt", name[k]); std::ofstream synthesisParameterFile(pname); synthesisParameterFile << "GUIDE "; synthesisParameterFile << GUIDE; synthesisParameterFile << std::endl; synthesisParameterFile << "STRENGTH "; synthesisParameterFile << STRENGTH; synthesisParameterFile << std::endl; synthesisParameterFile << "INITLEVEL "; synthesisParameterFile << INITLEVEL; synthesisParameterFile << std::endl; synthesisParameterFile << "BLOCSIZE "; synthesisParameterFile << BLOCSIZE; synthesisParameterFile << std::endl; synthesisParameterFile << "INITERR "; synthesisParameterFile << INITERR; synthesisParameterFile << std::endl; synthesisParameterFile << "INDEXWEIGHT "; synthesisParameterFile << INDEXWEIGHT; synthesisParameterFile << std::endl; synthesisParameterFile << "labelmapType "; synthesisParameterFile << labelmapType; synthesisParameterFile << std::endl; printf("TEXTURE: %s\n", name[0]); printf("\ninput size: (%d,%d)", width, height); printf("\noutput size: (%d,%d)\n", PSIZE + 2 * padding, PSIZE + 2 * padding); std::cout << "- (automatic) padding: " << padding << std::endl; std::cout << std::endl; example[k].reset(exalbedo[k].sizeX(), exalbedo[k].sizeY(), hview::hvColRGB<unsigned char>(0)); for (int ii = 0; ii < width; ii++) for (int jj = 0; jj < height; jj++) { example[k].update(ii, jj, exalbedo[k].get(ii, jj)); } std::cout << "--------------------------------------------" << std::endl; std::cout << "CONNECTED COMPONENTS EXTRACTION" << std::endl; std::cout << "--------------------------------------------\n" << std::endl; // - timer auto startTime = std::chrono::high_resolution_clock::now(); int nbLabels = 0; std::vector< hview::hvColRGB< unsigned char > > labelColors; //-------------------------------------------------------------------------------------- hview::hvPictRGB< unsigned char > featrndcol(example[pptbfid].sizeX(), example[pptbfid].sizeY(), hview::hvColRGB< unsigned char >(0)); switch (labelmapType) { // random case 0: std::cout << "labelmap: random" << std::endl; std::cout << std::endl; break; // classification case 1: { // at least one label (black for background) //nbLabels = 1; //labelColors.push_back( hvColRGB< unsigned char >( 0, 0, 0 ) ); // Load label map sprintf(pname, "%s_featcol_class.png", name[0]); int width, height, nrChannels; unsigned char* data = nullptr; //stbi_set_flip_vertically_on_load(1); SptImageHelper::loadImage( pname, width, height, nrChannels, data, desired_channels ); if (data == nullptr) { std::cout << "Failed to load image: " << pname << std::endl; assert(false); //return 1; } // Count nb features int c = 0; for (int xxx = 0; xxx < width * height; xxx++) { int r = data[c++]; int g = data[c++]; int b = data[c++]; hview::hvColRGB< unsigned char > labelColor(r, g, b); // Search color bool found = false; for (const auto& color : labelColors) { if (color == labelColor) { found = true; } } // Store color if not found if (!found) { labelColors.push_back(labelColor); } } nbLabels = labelColors.size(); std::cout << "labelmap: with classification" << std::endl; std::cout << "nb labels: " << nbLabels << std::endl; int xxx = 0; std::cout << "LABEL COLORS:" << std::endl; for (const auto& c : labelColors) { std::cout << static_cast<int>(c.RED()) << " " << static_cast<int>(c.GREEN()) << " " << static_cast<int>(c.BLUE()) << std::endl; } // Update label map for (int jj = 0; jj < featrndcol.sizeY(); jj++) { for (int ii = 0; ii < featrndcol.sizeX(); ii++) { featrndcol.update(ii, jj, hview::hvColRGB< unsigned char >(data[nrChannels * (ii + jj * width)], data[nrChannels * (ii + jj * width) + 1], data[nrChannels * (ii + jj * width) + 2])); } } char buff[256]; sprintf(buff, "%s_featcol.%s", name[pptbfid], "ppm"); FILE* fd = fopen(buff, "wb"); //if (fd == 0) { perror("cannot load file: "); return 1; } featrndcol.savePPM(fd, 1); fclose(fd); // Free memory SptImageHelper::freeImage(data); } break; default: break; } //-------------------------------------------------------------------------------------- const int MEDIANFILT = 5; const int EROSION = 1; hview::hvBitmap ffiltex; ffiltex.median(exseg[pptbfid], MEDIANFILT / 2, MEDIANFILT / 2); for (int kk = 0; kk < EROSION; kk++) ffiltex.erosion(3, 3); hview::hvPict< float > fpval(example[pptbfid].sizeX(), example[pptbfid].sizeY(), 1.0f); hview::hvBitmap excomp, ccomp, allfeat(example[pptbfid].sizeX(), example[pptbfid].sizeY(), false); excomp = ffiltex; const int MAX_FEAT = 1000; float featsizes[MAX_FEAT]; float meansize = 0.0; int nnfeatures = 0, largefeatures = 0; float vrand[MAX_FEAT]; std::vector<hview::hvVec2<int> > fcenters; //hvPictRGB<unsigned char> featrndcol(example[pptbfid].sizeX(), example[pptbfid].sizeY(), hvColRGB<unsigned char>(0)); //-------------------------------------------------------------------------------------- switch (labelmapType) { // classification case 1: { // Reset values for (int i = 0; i < MAX_FEAT; i++) { vrand[i] = 0.f; } // Fill random values per label vrand[0] = 0.1f + 0.9f * static_cast<float>(rand()) / static_cast<float>(RAND_MAX); //for ( int i = 1; i <= nbLabels; i++ ) for (int i = 1; i < nbLabels; i++) { const float v = 0.1f + 0.9f * static_cast<float>(rand()) / static_cast<float>(RAND_MAX); vrand[i] = v; } // BEWARE: update connected component (or label) counter //nnfeatures = nbLabels; } break; default: break; } //-------------------------------------------------------------------------------------- //if ( labelmapType == 0 ) // random //{ if (labelmapType == 0) // random { vrand[0] = 0.1f + 0.9f*(float)rand() / (float)RAND_MAX; } while (excomp.extractCC(ccomp)) { hview::hvColRGB<unsigned char> frndcol(50 + (unsigned char)((float)rand() / (float)RAND_MAX*200.0), 50 + (unsigned char)((float)rand() / (float)RAND_MAX*200.0), 50 + (unsigned char)((float)rand() / (float)RAND_MAX*200.0)); hview::hvVec2<int> min, max; ccomp.box(min, max); if ((max.X() - min.X() > 20 && max.Y() - min.Y() > 20) && (min.X() > 4 && max.X() < excomp.sizeX() - 1 - 4 && min.Y() > 4 && max.Y() < excomp.sizeY() - 1 - 4) || (max.X() - min.X() > 100 || max.Y() - min.Y() > 100)) { int ncount = 0; hview::hvVec2<int> bary(0, 0); float val = 0.f; if (labelmapType == 0) // random { val = 0.1f + 0.9f*(float)rand() / (float)RAND_MAX; vrand[nnfeatures + 1] = val; } int pixelcount = ccomp.count(); meansize += pixelcount; largefeatures++; printf("CComp : %d,%d \n", (min.X() + max.X()) / 2, (min.Y() + max.Y()) / 2); hview::hvBitmap ccompl; ccompl.dilatation(ccomp, 3, 3); for (int ii = min.X(); ii <= max.X(); ii++) for (int jj = min.Y(); jj <= max.Y(); jj++) if (ccompl.get(ii, jj)) { if (labelmapType == 1) // classification { // Retrieve class ID const hview::hvColRGB< unsigned char >& labelColor = featrndcol.get(ii, jj); // Search color int classID = 0; for (const auto& color : labelColors) { if (color == labelColor) { break; } classID++; } val = vrand[classID]; //printf( " %d", classID ); // for debug } fpval.update(ii, jj, val); if (labelmapType == 0) // random { featrndcol.update(ii, jj, frndcol); } ncount++; bary += hview::hvVec2<int>(ii, jj); } featsizes[nnfeatures] = (float)ncount / (float)(example[pptbfid].sizeX()* example[pptbfid].sizeY()); nnfeatures++; bary = hview::hvVec2<int>(bary.X() / ncount, bary.Y() / ncount); fcenters.push_back(bary); } allfeat |= ccomp; ~ccomp; excomp &= ccomp; } for (int ii = 0; ii < fpval.sizeX(); ii++) for (int jj = 0; jj < fpval.sizeY(); jj++) { if (!ffiltex.get(ii, jj)) fpval.update(ii, jj, vrand[0]); } printf("\nnfeat=%d\n", nnfeatures); // } // - timer auto endTime = std::chrono::high_resolution_clock::now(); float elapsedTime = static_cast<float>(std::chrono::duration_cast<std::chrono::milliseconds>(endTime - startTime).count()); std::cout << "\ntime: " << elapsedTime << " ms\n"; if (labelmapType == 1) // classification { nnfeatures = nbLabels - 1; // nnfeatures do not have background } // Apply the normalization const int EROD = 10; const float FEATPOWER = 0.1; hview::hvBitmap ffilt; ffilt.median(exseg[pptbfid], MEDIANFILT / 2, MEDIANFILT / 2); hview::hvBitmap ffeat; ffeat = ffilt; //ffeat.dilatation(EROD, EROD); hview::hvPict<unsigned char> featbw(ffeat, EROD, 255); unsigned char minbw, maxbw; featbw.minmax(minbw, maxbw); ~ffilt; ffeat = ffilt; //ffeat.dilatation(EROD/2, EROD/2); hview::hvPict<unsigned char> featbwr(ffeat, EROD, 255); unsigned char minbwr, maxbwr; featbwr.minmax(minbwr, maxbwr); hview::hvPict<float> featnormal(ffeat.sizeX(), ffeat.sizeY(), 0.0); hview::hvPictRGB<unsigned char> featdog(example[pptbfid].sizeX(), example[pptbfid].sizeY(), hview::hvColRGB<unsigned char>(0)); hview::hvPictRGB<unsigned char> featdogpastel(example[pptbfid].sizeX(), example[pptbfid].sizeY(), hview::hvColRGB<unsigned char>(0)); for (i = 0; i < example[pptbfid].sizeX(); i++) for (j = 0; j < example[pptbfid].sizeY(); j++) { float vbw = (float)featbw.get(i, j) / (float)maxbw; float vbwr = (float)featbwr.get(i, j) / (float)maxbwr; featnormal.update(i, j, vbw > vbwr ? vbw : vbwr); hview::hvColRGB<unsigned char> col = hview::hvColRGB<unsigned char>( (unsigned char)(100 + (int)(pow(vbw, FEATPOWER)*150.0)), 100 + (int)(pow(vbwr, FEATPOWER)*150.0), (unsigned char)(fpval.get(i, j)*150.0)); // WARNING: casting to uchar with x150 can erase and mix different labels (ex: 0.478 and 0.475) #if 0 // label map with classification if (labelmapType == 1) { const int labelID = std::max(0, static_cast<int>(std::floor(fpval.get(i, j) * nbLabels)) - 1); col[2] = static_cast<unsigned char>(labelID); } #endif //featdog.update(i, j, hvColRGB<unsigned char>(featbw.get(i, j), featbwr.get(i, j), (unsigned char)(255.0*fpval.get(i, j)))); featdog.update(i, j, col); featdogpastel.update(i, j, hview::hvColRGB<unsigned char>(150 + (unsigned char)(pow(vbw, 0.2)*100.0*(0.5*fpval.get(i, j) + 0.5)) + pow(vbwr, 0.2)*100.0)); //if (fpval.get(i, j) == 1.0f && featbw.get(i, j) == 255) printf("max val at %d,%d\n", i, j); //0*(pquant.getIndex(i,j)==imax?0:pifilt.get(i,j).RED()))); } char buff[256]; char* extension = "ppm"; sprintf(buff, "%s_feat.%s", name[pptbfid], extension); FILE* fd = fopen(buff, "wb"); // if (fd == 0) { perror("cannot load file:"); return 1; } featdog.savePPM(fd, 1); fclose(fd); sprintf(buff, "%s_feat_pastel.%s", name[pptbfid], extension); fd = fopen(buff, "wb"); // if (fd == 0) { perror("cannot load file:"); return 1; } featdogpastel.savePPM(fd, 1); fclose(fd); sprintf(buff, "%s_feat_pastel.%s", name[pptbfid], extension); fd = fopen(buff, "wb"); // if (fd == 0) { perror("cannot load file:"); return 1; } featdogpastel.savePPM(fd, 1); fclose(fd); hview::hvPictRGB<unsigned char> featnormalrgb(featnormal, 255.0); sprintf(buff, "%s_featnormal.%s", name[pptbfid], extension); fd = fopen(buff, "wb"); // if (fd == 0) { perror("cannot load file:"); return 1; } featnormalrgb.savePPM(fd, 1); fclose(fd); //printf( "Synthesis of plane...\n" ); hview::hvPictRGB<unsigned char> nouv(PSIZE + 2 * padding, PSIZE + 2 * padding, hview::hvColRGB<unsigned char>()); hview::hvPict<hview::hvVec2<int> > index(PSIZE + 2 * padding, PSIZE + 2 * padding, hview::hvVec2<int>(0)); hview::hvPict<float> pptbfpi(PSIZE + 2 * padding, PSIZE + 2 * padding, 0.f); hview::hvPict<float> ppval(PSIZE + 2 * padding, PSIZE + 2 * padding, 0.f); hview::hvPictRGB<unsigned char> pptbfrgb(PSIZE + 2 * padding, PSIZE + 2 * padding, 0.0); hview::hvPictRGB<unsigned char> pptbfbin(PSIZE + 2 * padding, PSIZE + 2 * padding, 0.0); std::cout << "\n--------------------------------------------" << std::endl; std::cout << "PPTBF SYNTHESIS" << std::endl; std::cout << "--------------------------------------------" << std::endl; // - timer startTime = std::chrono::high_resolution_clock::now(); //------------------------------------- // Launch PPTBF software generation computer pptbfshader( 1.f, pptbfpi, ppval ); //------------------------------------- // - timer endTime = std::chrono::high_resolution_clock::now(); elapsedTime = static_cast<float>(std::chrono::duration_cast<std::chrono::milliseconds>(endTime - startTime).count()); std::cout << "\ntime: " << elapsedTime << " ms\n"; //featpercent[pptbfid] = (float)exseg[pptbfid].count() / (float)(exseg[pptbfid].sizeX()*exseg[pptbfid].sizeY()); float pvmin, pvmax; pptbfpi.minmax(pvmin, pvmax); const int NHBINS = 128; float histopptbf[NHBINS]; hview::hvPictureMetrics::histogramm(pptbfpi, histopptbf, NHBINS, pvmin, pvmax); featpercent[pptbfid] = thresh[pptbfid]; float pptbfthresh = hview::hvPictureMetrics::computeThresh(1.0 - featpercent[pptbfid], histopptbf, NHBINS, pvmin, pvmax); thresh[pptbfid] = pptbfthresh; printf("\n%g percent = threshold for PPTBF %d is %g, min=%g, max=%g\n", featpercent[pptbfid], pptbfid, pptbfthresh, pvmin, pvmax); vvmin[pptbfid] = pvmin; vvmax[pptbfid] = pvmax; thresh[pptbfid + di] = thresh[pptbfid] * threshtransition; vvmin[pptbfid + di] = pvmin; vvmax[pptbfid + di] = pvmax; int ipara = 0; // file already exists, but threshold is different => it's the % instead of the real pptbf value to use for (ii = 0; ii < nouv.sizeX(); ii++) { //float transition = (float)ii / (float)nouv.sizeX(); for (jj = 0; jj < nouv.sizeY(); jj++) { //float x = (float)(ii*ZZ + shiftx*ZZ) / (float)SS + 10.0; //float y = (float)(jj*ZZ + shifty*ZZ) / (float)SS + 10.0; //float turb; float transition = (float)ii / (float)nouv.sizeX(); // +0.3*(1.0 - 2.5*hvNoise::turbulence((double)x*2.0, (double)y*2.0, 1.24, 0.0001)); if (transition < 0.25) transition = 0.0; else if (transition < 0.75) transition = (transition - 0.25) / 0.5; else transition = 1.0; if (TRANSITION) pptbfthresh = thresh[pptbfid] * (1.0 - transition) + thresh[pptbfid + di] * transition; //else pptbfthresh = thresh[pptbfid]; //float valf = (pptbfpi.get(ii, jj) - vvmin[pptbfid]) / (vvmax[pptbfid] - vvmin[pptbfid]); //float valf2 = (pptbfpi.get(ii, jj) - vvmin[pptbfid + 1]) / (vvmax[pptbfid + 1] - vvmin[pptbfid + 1]); float valf = pptbfpi.get(ii, jj); if (valf < 0.0) valf = 0.0; else if (valf > 1.0) valf = 1.0; unsigned char val = (unsigned char)(255.0*valf); pptbfrgb.update(ii, jj, hview::hvColRGB<unsigned char>(val, val, val)); //i = (int)((float)(ii*ZZ)*FSCALE + shiftx); //j = (int)((float)(jj*ZZ)*FSCALE + shifty); hview::hvColRGB<unsigned char> col1, col1b; hview::hvVec4<int> pos1; hview::hvVec4<int> vv1; col1 = pptbf_col1[pptbfid]; if (TRANSITION) col1b = pptbf_col1[pptbfid + di]; hview::hvColRGB<unsigned char> col2, col2b; hview::hvVec4<int> pos2; hview::hvVec4<int> vv2; col2 = pptbf_col2[pptbfid]; if (TRANSITION) col2b = pptbf_col2[pptbfid + di]; if (pptbfpi.get(ii, jj) > pptbfthresh) { if (TRANSITION) col1.interpolate(col1, col1b, transition); if (pptbfpi.get(ii, jj) < pptbfthresh*1.2) col1.interpolate(col2, col1, (pptbfpi.get(ii, jj) - pptbfthresh) / (pptbfthresh*1.2 - pptbfthresh)); nouv.update(ii, jj, col1); index.update(ii, jj, hview::hvVec2<int>(pos1.X(), pos1.Y())); pptbfbin.update(ii, jj, hview::hvColRGB<unsigned char>(255, 255, 255)); } else { if (TRANSITION) col2.interpolate(col2, col2b, transition); nouv.update(ii, jj, col2); index.update(ii, jj, hview::hvVec2<int>(256, 493)); pptbfbin.update(ii, jj, hview::hvColRGB<unsigned char>(0, 0, 0)); } } } sprintf(pname, "%s_col%s.%s", name[pptbfid], TRANSITION ? "_t" : "", extension); fd = fopen(pname, "wb"); nouv.savePPM(fd, 1); fclose(fd); sprintf(pname, "%s_pptbf%s.%s", name[pptbfid], TRANSITION ? "_t" : "", extension); fd = fopen(pname, "wb"); pptbfrgb.savePPM(fd, 1); fclose(fd); sprintf(pname, "%s_pptbf_bin%s.%s", name[pptbfid], TRANSITION ? "_t" : "", extension); fd = fopen(pname, "wb"); pptbfbin.savePPM(fd, 1); fclose(fd); float rangea = hview::hvPictureMetrics::computeThresh((1.0 - featpercent[pptbfid])*GUIDE, histopptbf, NHBINS, pvmin, pvmax); float rangeb = hview::hvPictureMetrics::computeThresh((1.0 - featpercent[pptbfid]) + featpercent[pptbfid] * (1.0 - GUIDE), histopptbf, NHBINS, pvmin, pvmax); float thresha = hview::hvPictureMetrics::computeThresh((1.0 - featpercent[pptbfid])*0.95, histopptbf, NHBINS, pvmin, pvmax); float threshb = hview::hvPictureMetrics::computeThresh((1.0 - featpercent[pptbfid]) + featpercent[pptbfid] * (1.0 - 0.95), histopptbf, NHBINS, pvmin, pvmax); printf("rangea=%g, rangeb=%g\n", rangea, rangeb); hview::hvPictRGB<unsigned char> pictdog(nouv.sizeX(), nouv.sizeY(), hview::hvColRGB<unsigned char>(0)); hview::hvPictRGB<unsigned char> pictdogpastel(nouv.sizeX(), nouv.sizeY(), hview::hvColRGB<unsigned char>(0)); hview::hvPictRGB<unsigned char> pictdogmask(nouv.sizeX(), nouv.sizeY(), hview::hvColRGB<unsigned char>(0)); hview::hvBitmap mask(nouv.sizeX(), nouv.sizeY(), false); hview::hvPict<float> ppvalue(nouv.sizeX(), nouv.sizeY(), 0.0); for (j = 0; j < nouv.sizeY(); j++) for (i = 0; i < nouv.sizeX(); i++) { float transition = (float)ii / (float)nouv.sizeX(); // +0.3*(1.0 - 2.5*hvNoise::turbulence((double)x*2.0, (double)y*2.0, 1.24, 0.0001)); if (transition < 0.25) transition = 0.0; else if (transition < 0.75) transition = (transition - 0.25) / 0.5; else transition = 1.0; if (TRANSITION) pptbfthresh = thresh[pptbfid] * (1.0 - transition) + thresh[pptbfid + di] * transition; float valf = pptbfpi.get(i, j); //if (valf < 0.0) valf = 0.0; else if (valf > 1.0) valf = 1.0; if (i >= 2 && j >= 2 && i <= nouv.sizeX() - 3 && j <= nouv.sizeY() - 3 && (valf<rangea || valf>rangeb)) mask.set(i, j, true); int bind = 1 + (int)((float)nnfeatures*(ppval.get(i, j)*0.5 + 0.5)); if (bind >= nnfeatures + 1) { bind = nnfeatures + 1; // BUG ? should be clamp to "nnfeatures" instead ? printf("\nWARNING: random selected ID (%d) seems to exceed nb labels or connected components (error?)", bind); } ppvalue.update(i, j, vrand[bind]); if (valf < pptbfthresh) ppvalue.update(i, j, vrand[0]); float vbw = 0.0; float vbwr = 0.0; float vnorm; if (valf < pptbfthresh) { vnorm = (1.0 - valf / pptbfthresh); vbwr = vnorm; } else { vnorm = (valf - pptbfthresh) / (pvmax - pptbfthresh); vbw = vnorm; } //pictnorm.update(i, j, vnorm); // Guidance map: pptbf hview::hvColRGB<unsigned char> col = hview::hvColRGB<unsigned char>( (unsigned char)(100 + (int)(pow(vbw, FEATPOWER)*150.0)), 100 + (int)(pow(vbwr, FEATPOWER)*150.0), (unsigned char)(150.0*ppvalue.get(i, j))); #if 0 // label map with classification if (labelmapType == 1) { const int labelID = std::max(0, static_cast<int>(std::floor(ppvalue.get(i, j) * nbLabels)) - 1); col[2] = static_cast<unsigned char>(labelID); } #endif pictdog.update(i, j, col); pictdogmask.update(i, j, mask.get(i, j) ? pictdog.get(i, j) : hview::hvColRGB<unsigned char>(0)); if (valf < pptbfthresh) pictdogpastel.update(i, j, pptbf_col2[pptbfid]); else { pictdogpastel.update(i, j, pptbf_col1[pptbfid]); //float colc = pow(vbw, 0.2)*(0.5*ppvalue.get(i, j) + 0.5); //pictdogpastel.update(i, j, hvColRGB<unsigned char>((unsigned char)((float)pptbf_col1[pptbfid].RED()*colc), (unsigned char)((float)pptbf_col1[pptbfid].GREEN()*colc), (unsigned char)((float)pptbf_col1[pptbfid].BLUE()*colc))); //pictdogpastel.update(i, j, hvColRGB<unsigned char>(150 + (unsigned char)(pow(vbw, 0.2)*100.0*(0.5*ppvalue.get(i, j) + 0.5)) + pow(vbwr, 0.2)*100.0)); } } char fname[256]; sprintf(fname, "%s_pptbf_feat.%s", name[pptbfid], extension); fd = fopen(fname, "wb"); // if (fd == 0) { perror("cannot load file:"); return 1; } pictdog.savePPM(fd, 1); fclose(fd); sprintf(fname, "%s_pptbf_featpastel.%s", name[pptbfid], extension); fd = fopen(fname, "wb"); // if (fd == 0) { perror("cannot load file:"); return 1; } pictdogpastel.savePPM(fd, 1); fclose(fd); sprintf(fname, "%s_pptbf_featmask.%s", name[pptbfid], extension); fd = fopen(fname, "wb"); // if (fd == 0) { perror("cannot load file:"); return 1; } pictdogmask.savePPM(fd, 1); fclose(fd); hview::hvPictRGB<unsigned char> res, resfeat; hview::hvArray2<hview::hvVec2<int> > iindex, indexx; hview::hvPictRGB<unsigned char> pictdogextrapol; hview::hvBitmap maskextrapol; if (TRANSITION) { pictdogextrapol.clone(pictdog, 0, 0, pictdog.sizeX() - 1, pictdog.sizeY() - 1); maskextrapol = mask; } else { int ppx = nouv.sizeX() - 2 * PSIZE; if (ppx < 0) ppx = 0; pictdogextrapol.clone(pictdog, ppx, 0, pictdog.sizeX() - 1, pictdog.sizeY() - 1); maskextrapol.reset(nouv.sizeX() - ppx, nouv.sizeY(), false); for (int ii = 0; ii < maskextrapol.sizeX(); ii++) for (int jj = 0; jj < maskextrapol.sizeY(); jj++) if (mask.get(ii + ppx, jj)) maskextrapol.set(ii, jj, true); } /////////////////////////////////////////////////////////////// std::cout << "\n--------------------------------------------" << std::endl; std::cout << "COLOR/MATERIAL SYNTHESIS" << std::endl; std::cout << "--------------------------------------------" << std::endl; // - timer startTime = std::chrono::high_resolution_clock::now(); // User customizable parameter(s) const int nbCorrectionPasses = 2; const bool useSmartInitialization = false; // Launch color/material synthesis res.execute_semiProceduralTextureSynthesis( const_cast<char*>(name[pptbfid]), STOPATLEVEL, shiftx, shifty, example[pptbfid], featdog, 0.8, // weight color vs distance STRENGTH, // weight to accentuate or diminish guidance (as a power) 3.0*INDEXWEIGHT*INDEXWEIGHT, // label weight 2, // neighbor size for comparing neighbor candidate INITLEVEL, // level at which to start pcst synthesis vs smart initialization BLOCSIZE, // size of copied block of UV at smart initialization INITERR, // maximum acceptable error for smart initialization maskextrapol, // guidance mask (binary pptbf) pictdogextrapol, // guidance (pptbf) indexx, // main uv map (i.e. indirection map) // user customizable parameter(s) nbCorrectionPasses, useSmartInitialization ); // - timer endTime = std::chrono::high_resolution_clock::now(); elapsedTime = static_cast<float>(std::chrono::duration_cast<std::chrono::milliseconds>(endTime - startTime).count()); std::cout << "- time: " << elapsedTime << " ms\n"; hview::hvPictRGB<unsigned char> synthalbedo(indexx.sizeX(), indexx.sizeY(), hview::hvColRGB<unsigned char>()); synthalbedo.imagefromindex(exalbedo[pptbfid], indexx); sprintf(buff, "%s_semiproc_albedo.%s", name[pptbfid], extension); fd = fopen(buff, "wb"); // if (fd == 0) { perror("cannot load file:"); return 1; } synthalbedo.savePPM(fd, 1); fclose(fd); hview::hvPictRGB<unsigned char> synthpastel(indexx.sizeX(), indexx.sizeY(), hview::hvColRGB<unsigned char>()); synthpastel.imagefromindex(featdogpastel, indexx); sprintf(buff, "%s_semiproc_featpastel.%s", name[pptbfid], extension); fd = fopen(buff, "wb"); //if (fd == 0) { perror("cannot load file:"); return 1; } synthpastel.savePPM(fd, 1); fclose(fd); hview::hvPictRGB<unsigned char> synthfeat(indexx.sizeX(), indexx.sizeY(), hview::hvColRGB<unsigned char>()); synthfeat.imagefromindex(featdog, indexx); sprintf(buff, "%s_semiproc_feat.%s", name[pptbfid], extension); fd = fopen(buff, "wb"); // if (fd == 0) { perror("cannot load file:"); return 1; } synthfeat.savePPM(fd, 1); fclose(fd); printf("\nfinish.(press return)\n"); } /****************************************************************************** * Semi-procedural texture synthesis parameters ******************************************************************************/ void SptBasicHviewInterface::setExemplarName( const char* pText ) { mExemplarName = std::string( pText ); } /****************************************************************************** * Semi-procedural texture synthesis parameters ******************************************************************************/ void SptBasicHviewInterface::setGUIDE( const float pValue ) { GUIDE = pValue; } /****************************************************************************** * Semi-procedural texture synthesis parameters ******************************************************************************/ void SptBasicHviewInterface::setSTRENGTH( const float pValue ) { STRENGTH = pValue; } /****************************************************************************** * Semi-procedural texture synthesis parameters ******************************************************************************/ void SptBasicHviewInterface::setINITLEVEL( const int pValue ) { INITLEVEL = pValue; } /****************************************************************************** * Semi-procedural texture synthesis parameters ******************************************************************************/ void SptBasicHviewInterface::setBLOCSIZE( const int pValue ) { BLOCSIZE = pValue; } /****************************************************************************** * Semi-procedural texture synthesis parameters ******************************************************************************/ void SptBasicHviewInterface::setINITERR( const float pValue ) { INITERR = pValue; } /****************************************************************************** * Semi-procedural texture synthesis parameters ******************************************************************************/ void SptBasicHviewInterface::setINDEXWEIGHT( const float pValue ) { INDEXWEIGHT = pValue; }
48,541
C++
.cpp
1,119
40.6479
396
0.597734
ASTex-ICube/semiproctex
39
8
2
LGPL-2.1
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,899
hvNoise.cpp
ASTex-ICube_semiproctex/Semiproc_synthesis_Src/3rdParty/Externals/hview/hvNoise.cpp
/* * Publication: Semi-Procedural Textures Using Point Process Texture Basis Functions * Computer Graphics Forum (EGSR 2020 special issue) * Authors: P. Guehl , R. AllEgre , J.-M. Dischler, B. Benes , and E. Galin * * Code author: Pascal Guehl */ /** * @version 1.0 */ #include "hvNoise.h" /****************************************************************************** ******************************* INCLUDE SECTION ****************************** ******************************************************************************/ /****************************************************************************** ****************************** NAMESPACE SECTION ***************************** ******************************************************************************/ // Project using namespace hview; /****************************************************************************** ************************* DEFINE AND CONSTANT SECTION ************************ ******************************************************************************/ /****************************************************************************** ***************************** TYPE DEFINITION ******************************** ******************************************************************************/ /****************************************************************************** ***************************** METHOD DEFINITION ****************************** ******************************************************************************/ double hvNoise::rnd_tab[MAX_NOISE_RAND] = { -0.20707, 0.680971, -0.293328, -0.106833, -0.362614, 0.772857, -0.968834, 0.16818, -0.681263, -0.232568, 0.382009, -0.882282, 0.799709, -0.672908, -0.681857, 0.0661294, 0.208288, 0.165398, -0.460058, -0.219044, -0.413199, 0.484755, -0.402949, -0.848924, -0.190035, 0.714756, 0.883937, 0.325661, 0.692952, -0.99449, -0.0752415, 0.0651921, 0.575753, -0.468776, 0.965505, -0.38643, 0.20171, 0.217431, -0.575122, 0.77179, -0.390686, -0.69628, -0.324676, -0.225046, 0.28722, 0.507107, 0.207232, 0.0632565, -0.0812794, 0.304977, -0.345638, 0.892741, -0.26392, 0.887781, -0.985143, 0.0331999, -0.454458, -0.951402, 0.183909, -0.590073, 0.755387, -0.881263, -0.478315, -0.394342, 0.78299, -0.00360388, 0.420051, -0.427172, 0.729847, 0.351081, -0.08302, 0.919271, 0.549351, -0.246897, -0.542722, -0.290932, -0.399364, 0.339532, 0.437933, 0.131909, 0.648931, -0.218776, 0.637533, 0.688017, -0.639064, 0.886792, -0.150226, 0.0413315, -0.868712, 0.827016, 0.765169, 0.522728, -0.202155, 0.376514, 0.523097, -0.189982, -0.749498, -0.0307322, -0.555075, 0.746242, 0.0576438, -0.997172, 0.721028, -0.962605, 0.629784, -0.514232, -0.370856, 0.931465, 0.87112, 0.618863, -0.0157817, -0.559729, 0.152707, -0.421942, -0.357866, -0.477353, -0.652024, -0.996365, -0.910432, -0.517651, -0.169098, 0.403249, -0.556309, 0.00782073, -0.86594, -0.213873, -0.0410469, -0.563716, -0.560977, 0.832406, -0.299556, -0.614612, -0.57753, 0.267363, -0.892869, 0.566823, -0.938652, -0.111807, -0.647174, 0.86436, 0.819297, -0.0543103, 0.743391, 0.391135, 0.860379, -0.0898189, -0.202866, 0.786608, 0.387094, 0.677469, 0.479398, 0.302539, 0.356308, 0.154425, -0.453763, 0.870776, 0.323878, -0.905175, -0.253923, 0.23639, -0.702744, -0.245389, 0.289183, -0.948624, 0.682761, -0.845962, 0.485268, -0.488028, 0.803688, -0.244705, -0.36094, -0.57713, 0.297065, -0.49737, -0.542711, -0.498156, 0.886442, -0.72657, -0.459878, 0.0974144, -0.351957, 0.73016, -0.406593, 0.360119, 0.666294, 0.752615, 0.299329, -0.853769, 0.797094, -0.492837, 0.222637, 0.68378, 0.664039, -0.254826, 0.514096, -0.78157, 0.701624, 0.118659, 0.715161, -0.313806, 0.383539, -0.309605, 0.787169, 0.917416, -0.75653, 0.963089, -0.88995, 0.229553, -0.923747, -0.247055, 0.0512097, -0.436152, 0.121076, 0.214486, 0.632879, -0.10693, -0.945777, -0.056292, -0.430203, -0.414553, -0.60864, -0.964841, 0.659198, 0.146331, -0.790439, 0.465953, -0.761805, -0.552223, 0.894506, 0.478103, 0.642714, 0.652263, -0.49804, -0.487009, -0.323614, -0.223557, 0.054637, -0.467182, -0.197559, 0.741789, -0.908216, -0.410852, -0.211507, 0.120005, -0.378358, 0.645154, -0.049037, -0.817713, -0.475198, 0.834088, 0.956872, -0.335813, 0.804148, -0.51873, -0.253671, 0.504572, -0.0843452, 0.801256, -0.154211, 0.131847, 0.940924, -0.292258, -0.136987, -0.641817, -0.569362, -0.325646, -0.0912645, -0.910549, 0.367765, -0.875702, 0.102751, -0.367658, -0.463564, 0.00153196, -0.874926, 0.929653, 0.459152, 0.612631, -0.696051, 0.410036, 0.459915, 0.685132, 0.235857, 0.910896, -0.0412238, 0.054171, -0.941227, 0.215224, -0.904861, 0.185539, -0.194706, 0.808789, -0.339738, -0.378325, 0.70989, 0.468299, -0.802747, -0.319083, -0.196521, 0.970334, 0.25919, 0.663925, -0.125761, 0.582453, -0.881076, -0.72973, 0.0876478, 0.860903, 0.769798, -0.220211, -0.170885, 0.713725, -0.426483, -0.784487, 0.153352, 0.555204, -0.715498, 0.617354, 0.496188, -0.17995, -0.0497684, -0.311081, -0.166402, -0.952704, 0.051622, 0.435783, -0.527955, 0.38973, 0.559901, 0.525501, -0.756875, -0.258964, 0.856503, 0.532013, -0.420841, 0.967321, -0.143786, -0.924374, 0.196653, -0.968809, 0.513448, -0.738642, -0.250866, -0.565008, 0.155594, -0.588673, 0.574042, 0.496738, -0.0893272, -0.429463, 0.70044, -0.0999849, 0.670024, -0.139508, -0.338008, 0.901744, -0.502254, -0.286412, -0.164259, -0.00589371, 0.770586, 0.126331, 0.371001, 0.935519, -0.635262, 0.135611, -0.940671, -0.592076, -0.68447, 0.0951887, -0.592019, -0.577427, -0.865412, -0.613805, 0.803043, 0.564099, -0.39482, -0.155984, 0.979051, 0.594241, -0.225057, -0.636119, -0.550537, 0.474766, 0.0670141, 0.329472, -0.596338, -0.0623523, 0.132995, -0.805072, -0.445953, -0.965377, 0.127768, 0.773879, -0.85962, -0.875958, -0.493386, -0.385871, 0.79328, -0.731853, 0.89542, -0.141091, -0.843747, 0.567334, -0.112659, -0.157636, 0.403773, -0.620359, -0.74756, -0.503881, 0.315856, -0.724989, -0.354449, 0.645029, -0.972318, 0.847415, -0.247293, 0.164137, -0.477254, -0.172582, 0.375393, 0.507442, -0.657344, -0.741592, -0.682019, -0.414483, 0.715187, -0.442246, 0.376847, 0.677779, 0.629953, -0.902771, -0.854116, -0.138042, 0.499652, -0.696091, -0.175465, -0.794968, 0.522245, 0.283572, 0.469819, 0.0948274, -0.800236, 0.464648, 0.0576595, 0.038949, -0.427001, 0.894641, -0.147727, -0.0114098, 0.40495, -0.483555, 0.622736, 0.760873, -0.997745, -0.785802, -0.453497, 0.967972, -0.277754, 0.633599, 0.710523, -0.421174, 0.998972, -0.982482, -0.872429, 0.935388, 0.366325, -0.396888, 0.450846, 0.84717, 0.298028, 0.831535, 0.0722433, 0.953355, -0.533049, -0.162882, 0.163758, 0.560595, -0.59966, 0.802104, -0.741726, 0.857332, 0.529727, -0.0405177, 0.112755, -0.975824, -0.232527, -0.24467, 0.457103, 0.0876135, 0.355111, 0.179531, -0.434472, -0.784347, -0.402533, 0.057541, 0.810026, -0.125382, 0.902344, -0.535312, 0.0399954, 0.233073, -0.623447, 0.958511, 0.00639474, -0.679882, 0.0790659, -0.614876, -0.501872, -0.339625, -0.698238, 0.245166, -0.576554, 0.887646, 0.244024, -0.572648, -0.0526508, 0.685447, -0.117632, -0.761956, 0.840836, 0.348531, -0.670558, 0.560047, 0.419046, -0.630359, 0.553467, -0.569617, -0.490988, 0.325722, 0.921231, 0.884165, 0.616011, 0.594694, 0.972902, 0.399779, 0.329042, -0.764266, 0.379393, -0.68921, -0.344626, -0.097562, -0.176869, 0.0149344, 0.692548, 0.649795, 0.137582, 0.383956, -0.719118, 0.694652, 0.402503, -0.5849, -0.866093, -0.121557, 0.689953, -0.397973, -0.321879, 0.0748543, -0.934146, 0.757382, -0.637111, 0.929531, 0.455039, -0.109972, 0.598553, -0.00921971, -0.337852, -0.692814, 0.474436, -0.102178, -0.299422, 0.236665, 0.883008, -0.724233, 0.517349, -0.910394, 0.173275, 0.315035, -0.980193, 0.933607, -0.327466, 0.689187, 0.223563, -0.975296, 0.7046, 0.0224042, -0.531078, 0.34089, 0.604275, -0.879452, 0.52088, 0.237137, 0.848053, -0.276448, -0.592991, -0.348802, 0.112302, 0.748835, 0.896259, -0.939266, -0.189234, 0.533631, 0.323923, 0.737031, 0.588107, 0.138091, 0.17416, 0.151135, 0.146229, -0.438567, 0.4982, -0.161338, 0.602722, -0.997772, -0.663456, 0.0747519, 0.929268, 0.844336, -0.803741, 0.58706, -0.347807, 0.68648, -0.914757, -0.240175, -0.666555, -0.198301, -0.694225, -0.345168, -0.0395932, 0.289883, -0.752425, 0.275475, 0.485683, 0.780465, 0.790232, -0.810475, 0.758027, -0.207396, -0.973497, 0.547203, 0.0139524, -0.762494, -0.841653, 0.107478, -0.84642, 0.553916, -0.690491, -0.17762, -0.942622, 0.636364, 0.261143, -0.687253, 0.222471, 0.111039, 0.775731, -0.0331696, -0.325886, -0.768171, -0.83886, -0.0455701, -0.738002, 0.336049, 0.378831, -0.99628, -0.439122, -0.426069, 0.56223, 0.947077, -0.704819, -0.302501, -0.0665605, -0.301488, 0.789032, -0.216332, -0.654522, 0.152676, 0.853504, -0.374663, -0.00410563, -0.551168, -0.134369, 0.435965, 0.125214, 0.859039, 0.828424, -0.207817, 0.00542223, 0.255695, -0.156154, 0.231101, 0.421414, -0.511748, 0.753763, -0.499045, -0.26024, 0.132566, -0.564272, -0.456005, -0.961464, -0.16984, 0.265878, 0.308314, -0.460366, -0.0486212, -0.878744, -0.588512, -0.452418, -0.480284, 0.685756, 0.515324, -0.530612, 0.429637, 0.101136, 0.550935, 0.387332, -0.0366921, 0.676956, -0.778804, 0.606455, 0.730367, 0.606859, 0.59914, 0.0323113, -0.531947, 0.755581, 0.262923, 0.990242, 0.976722, -0.439991, -0.0811486, -0.0807913, 0.939347, 0.0632279, 0.553093, 0.411404, -0.124347, -0.136165, -0.959233, -0.619912, 0.185786, -0.738866, -0.919931, 0.185369, -0.3999, 0.713647, 0.0921651, -0.3001, 0.606923, -0.336502, 0.149248, 0.329354, -0.903224, 0.228558, 0.409017, 0.597411, 0.838132, 0.800225, -0.679005, -0.849974, 0.066663, 0.435656, 0.936607, -0.0771584, -0.211812, 0.484105, 0.940352, -0.850672, -0.992062, 0.178693, 0.994419, 0.172109, 0.429005, -0.845299, 0.155544, 0.368904, -0.0838963, -0.123131, 0.514225, -0.463254, -0.316715, -0.218999, -0.113225, -0.181078, -0.49629, -0.774654, 0.956039, 0.640184, 0.804682, -0.0728759, 0.333761, -0.524985, 0.132087, 0.907606, 0.764773, 0.855232, 0.756395, -0.279823, -0.70013, -0.522577, -0.95987, 0.180812, 0.45117, 0.154243, 0.267937, 0.406582, -0.137258, -0.370685, -0.0897717, -0.201184, 0.16377, -0.187431, 0.486166, 0.942996, -0.26433, -0.933307, 0.329012, 0.153509, 0.964356, -0.0324244, -0.564532, 0.640186, 0.0410044, -0.939893, 0.280686, -0.256316, -0.0724265, 0.0296069, -0.136661, 0.262995, 0.156279, -0.69113, 0.453271, -0.878359, 0.656072, -0.752054, -0.528582, 0.186816, -0.204273, -0.198698, 0.843176, 0.321241, 0.835749, -0.646054, -0.981633, 0.220718, -0.445718, 0.339949, -0.0889146, -0.562843, -0.948627, -0.864842, -0.670193, -0.470315, 0.768155, 0.168599, 0.372232, 0.503568, 0.241067, 0.0384121, 0.861864, 0.723146, 0.735475, 0.78832, -0.403295, 0.111575, 0.888819, 0.456458, -0.861308, -0.375725, 0.0924894, 0.0126309, 0.550513, 0.308125, -0.662566, 0.221904, 0.120679, -0.505715, -0.544765, 0.5873, -0.774288, 0.235227, -0.550015, 0.0138385, -0.64114, -0.441786, 0.313562, 0.288163, 0.587974, 0.696802, -0.743927, 0.876665, -0.347592, 0.563469, 0.603839, 0.31075, -0.787441, 0.381486, 0.189887, 0.857299, -0.150132, 0.79965, 0.388627, 0.978384, 0.984722, -0.176776, -0.939742, 0.886053, 0.42117, 0.517951, -0.363949, 0.32082, 0.508184, -0.652452, -0.0113876, 0.458137, -0.523753, -0.989305, 0.218567, -0.0866277, -0.804653, 0.229887, -0.791075, -0.583133, 0.0174403, 0.746333, -0.0597281, -0.483113, -0.594472, 0.0833201, -0.155518, -0.803679, -0.613321, 0.902488, -0.346171, -0.478224, 0.45257, 0.0966891, 0.559465, -0.749715, -0.895227, 0.399409, -0.657407, -0.0252426, 0.82075, -0.840023, -0.670942, 0.0760187, -0.401039, 0.108451, -0.579594, -0.945201, -0.492007, 0.142416, -0.519982, -0.764514, -0.32379, -0.705026, -0.558962, 0.265189, 0.0579748, 0.629764, -0.375703, -0.916671, -0.976436, 0.552299, -0.0888248, 0.321525, -0.452217, 0.280738, 0.141571, 0.530024, -0.496806, 0.493166, -0.034681, 0.740796, -0.434634, -0.371416, 0.462175, 0.100296, -0.441395, 0.28735, 0.287906, -0.525333, -0.958905, 0.63229, -0.439815, -0.209011, -0.340195, 0.768903, 0.857426, 0.580399, -0.309656, -0.427039, 0.787087, 0.789257, -0.61095, -0.716271, 0.839248, -0.114208, -0.220958, -0.00560474, -0.540353, 0.981056, 0.505123, -0.292023, -0.731658, 0.879887, 0.94177, -0.69709, -0.538658, 0.361588, -0.877064, -0.860003, 0.0400107, -0.350923, -0.13797, -0.630015, -0.475121, -0.0465513, 0.00653064, 0.653369, -0.833781, 0.578648, -0.233113 }; unsigned int hvNoise::P[MAX_NOISE_RAND] = { 673, 514, 228, 3, 157, 394, 315, 202, 123, 20, 606, 878, 605, 77, 926, 117, 581, 850, 1019, 282, 665, 939, 604, 814, 7, 1006, 922, 27, 28, 835, 30, 822, 285, 255, 851, 400, 330, 927, 38, 39, 119, 240, 176, 391, 295, 142, 191, 67, 379, 49, 50, 93, 398, 873, 286, 127, 693, 669, 793, 1020, 559, 278, 140, 410, 430, 411, 46, 47, 736, 13, 481, 160, 246, 772, 318, 82, 367, 660, 78, 291, 863, 445, 727, 483, 745, 968, 622, 894, 838, 661, 90, 91, 335, 700, 94, 994, 549, 97, 945, 161, 486, 340, 8, 418, 104, 303, 344, 232, 588, 45, 503, 615, 284, 787, 71, 728, 544, 691, 762, 149, 634, 452, 996, 203, 505, 178, 58, 638, 220, 260, 130, 139, 934, 16, 958, 631, 194, 967, 511, 195, 441, 181, 1015, 970, 999, 907, 911, 458, 815, 252, 808, 151, 53, 672, 671, 929, 658, 697, 251, 215, 819, 846, 267, 226, 689, 239, 518, 836, 210, 68, 771, 171, 943, 336, 235, 685, 893, 270, 349, 839, 180, 914, 182, 125, 901, 504, 597, 978, 862, 189, 783, 976, 1009, 844, 66, 859, 806, 109, 530, 871, 896, 539, 805, 348, 204, 205, 417, 720, 128, 237, 992, 25, 991, 773, 214, 159, 977, 80, 841, 219, 73, 292, 465, 813, 320, 225, 163, 227, 993, 229, 230, 231, 913, 407, 904, 371, 256, 872, 238, 65, 833, 306, 242, 243, 385, 831, 995, 148, 341, 22, 713, 334, 192, 253, 965, 100, 201, 257, 294, 321, 809, 590, 343, 959, 188, 853, 902, 95, 905, 633, 366, 383, 5, 652, 937, 135, 494, 710, 183, 395, 280, 325, 480, 308, 670, 92, 974, 287, 612, 431, 855, 589, 607, 677, 722, 949, 342, 353, 523, 299, 300, 301, 356, 738, 450, 305, 402, 268, 359, 854, 576, 196, 116, 313, 908, 548, 316, 538, 377, 168, 572, 690, 459, 307, 887, 85, 326, 533, 856, 51, 798, 437, 746, 111, 107, 600, 816, 389, 1022, 382, 743, 567, 358, 528, 923, 439, 323, 223, 103, 373, 350, 351, 32, 776, 397, 29, 245, 715, 216, 442, 766, 361, 521, 19, 912, 224, 427, 752, 368, 234, 254, 174, 546, 478, 363, 208, 34, 74, 378, 155, 447, 463, 425, 384, 108, 566, 721, 150, 388, 337, 825, 37, 989, 915, 261, 279, 675, 885, 666, 596, 903, 401, 571, 24, 852, 657, 75, 169, 36, 409, 990, 560, 786, 1018, 324, 415, 502, 346, 63, 707, 900, 547, 740, 579, 455, 218, 18, 580, 428, 244, 531, 289, 432, 433, 906, 701, 436, 331, 414, 88, 297, 200, 131, 443, 115, 594, 703, 217, 129, 678, 552, 406, 121, 453, 870, 561, 884, 86, 310, 562, 557, 823, 462, 381, 1, 986, 102, 467, 920, 969, 477, 298, 52, 626, 474, 355, 471, 770, 587, 42, 281, 118, 479, 613, 592, 83, 784, 365, 488, 360, 765, 491, 492, 522, 731, 647, 137, 529, 498, 4, 500, 617, 11, 540, 273, 464, 328, 507, 508, 490, 197, 369, 364, 15, 961, 290, 988, 264, 629, 1007, 987, 495, 81, 272, 524, 824, 166, 527, 193, 653, 1008, 880, 532, 889, 69, 535, 536, 812, 723, 712, 955, 422, 542, 718, 637, 954, 510, 421, 794, 236, 120, 868, 412, 608, 277, 79, 556, 555, 309, 403, 213, 434, 212, 898, 973, 493, 732, 35, 170, 569, 570, 725, 57, 709, 769, 938, 472, 619, 578, 761, 515, 802, 749, 352, 910, 698, 302, 956, 435, 399, 623, 444, 10, 136, 473, 779, 262, 405, 598, 526, 475, 897, 602, 739, 879, 370, 283, 271, 944, 89, 610, 792, 599, 429, 639, 132, 616, 803, 618, 936, 59, 259, 33, 925, 696, 250, 734, 627, 724, 826, 630, 628, 152, 985, 877, 635, 222, 101, 892, 960, 591, 931, 187, 456, 834, 916, 646, 54, 789, 179, 680, 651, 1004, 857, 460, 64, 206, 748, 156, 499, 184, 0, 952, 778, 664, 869, 269, 759, 979, 843, 112, 23, 941, 942, 496, 258, 624, 714, 656, 611, 338, 962, 1001, 683, 684, 935, 643, 681, 275, 413, 509, 207, 692, 755, 1011, 860, 818, 122, 70, 828, 662, 21, 84, 470, 963, 705, 550, 380, 387, 154, 764, 96, 339, 575, 733, 449, 317, 717, 788, 497, 134, 512, 781, 767, 393, 867, 241, 1021, 553, 519, 797, 593, 642, 757, 729, 735, 534, 737, 583, 791, 72, 668, 742, 14, 1013, 890, 585, 141, 565, 830, 795, 751, 296, 753, 754, 485, 849, 26, 758, 980, 332, 423, 747, 625, 327, 345, 645, 114, 87, 347, 609, 420, 774, 319, 322, 655, 162, 777, 883, 595, 780, 957, 782, 304, 31, 785, 173, 167, 649, 760, 153, 1012, 614, 948, 886, 601, 796, 730, 997, 799, 659, 333, 489, 874, 804, 667, 875, 807, 790, 933, 810, 848, 506, 60, 487, 586, 372, 817, 636, 221, 98, 821, 554, 708, 876, 964, 124, 165, 469, 829, 704, 248, 641, 741, 543, 288, 858, 953, 147, 454, 840, 12, 76, 190, 461, 845, 837, 847, 44, 891, 687, 158, 516, 265, 199, 482, 1000, 971, 266, 654, 438, 861, 177, 525, 864, 865, 468, 702, 551, 56, 568, 408, 390, 811, 476, 679, 881, 558, 632, 249, 314, 41, 882, 621, 577, 396, 711, 55, 888, 138, 145, 133, 311, 448, 603, 895, 983, 110, 563, 744, 172, 650, 564, 209, 775, 113, 573, 376, 211, 185, 688, 146, 582, 517, 584, 424, 620, 917, 918, 919, 866, 921, 676, 827, 924, 43, 975, 966, 928, 466, 930, 233, 932, 644, 446, 99, 106, 501, 768, 440, 998, 198, 820, 175, 541, 695, 946, 329, 186, 719, 950, 951, 357, 17, 545, 263, 40, 726, 386, 947, 756, 404, 537, 374, 62, 640, 247, 457, 686, 520, 143, 842, 126, 763, 2, 451, 513, 663, 682, 706, 972, 981, 982, 9, 984, 426, 694, 144, 674, 419, 362, 105, 416, 832, 48, 909, 274, 1002, 574, 293, 164, 484, 699, 1003, 312, 354, 276, 801, 648, 940, 1010, 800, 1005, 899, 1014, 61, 1016, 1017, 392, 716, 6, 750, 375, 1023 }; hvnoise_vec hvNoise::G[MAX_NOISE_RAND] = { { -0.995337,-0.0963314,0.00495357 }, { -0.127269,-0.895402,-0.426682 }, { -0.584669,-0.639987,-0.498577 }, { -0.256759,-0.0351604,-0.965836 }, { 0.230517,0.0496408,-0.971801 }, { -0.157628,0.973101,-0.168009 }, { -0.39926,0.901399,-0.167542 }, { -0.626804,-0.141564,-0.766209 }, { -0.807439,0.550296,-0.212643 }, { 0.506836,0.774449,-0.37861 }, { -0.502156,0.551161,-0.666379 }, { 0.766853,0.641784,0.00707779 }, { -0.286142,-0.941352,0.178827 }, { -0.0441219,-0.0135373,0.998934 }, { -0.855989,-0.408854,-0.316419 }, { -0.881202,-0.446996,0.153875 }, { -0.140249,-0.254445,0.956863 }, { -0.24534,-0.17324,-0.953832 }, { -0.617697,-0.569507,0.542321 }, { 0.753917,0.495649,-0.431208 }, { -0.573983,-0.1481,0.805363 }, { -0.81193,0.5261,-0.252961 }, { -0.452386,-0.705251,-0.545865 }, { -0.242218,-0.870244,-0.428958 }, { -0.950431,0.31004,-0.0235713 }, { 0.802699,0.565195,-0.19034 }, { -0.746878,0.664283,0.030028 }, { -0.896907,0.153356,-0.414778 }, { -0.748329,-0.202457,0.631676 }, { -0.528151,0.840434,0.121355 }, { -0.0162022,-0.130013,-0.99138 }, { -0.584409,0.137181,0.79978 }, { -0.789821,-0.492396,-0.365689 }, { 0.0624474,0.150884,0.986577 }, { -0.902876,0.311719,-0.29605 }, { -0.270693,0.88754,-0.372825 }, { 0.964165,0.0552917,0.259479 }, { 0.98341,0.171571,0.0588914 }, { 0.789046,0.394704,0.47076 }, { 0.0946113,0.249194,0.963821 }, { 0.897137,-0.366363,-0.246827 }, { -0.391713,-0.531864,-0.750787 }, { -0.198871,0.96269,-0.183518 }, { 0.00930338,-0.985714,0.16817 }, { 0.550144,-0.308657,0.775933 }, { 0.541166,-0.664553,0.515275 }, { -0.173206,-0.440895,0.880688 }, { -0.107763,0.682367,-0.723023 }, { 0.094759,0.165702,-0.981613 }, { 0.105035,-0.730918,-0.674335 }, { -0.124068,0.0584148,-0.990553 }, { -0.900757,0.433876,-0.0197054 }, { -0.279353,0.0175174,-0.960029 }, { -0.862581,0.450873,-0.229493 }, { 0.0118461,0.0393322,0.999156 }, { 0.262375,0.262377,0.928611 }, { -0.158975,0.415805,-0.895452 }, { 0.976371,-0.0116447,-0.215789 }, { -0.27176,-0.916866,0.292409 }, { -0.54853,-0.827749,-0.118094 }, { 0.686411,-0.448915,-0.572115 }, { -0.632621,-0.77415,-0.0219575 }, { 0.887597,0.135558,0.440223 }, { 0.728919,0.510989,0.455596 }, { 0.380389,-0.168086,0.909423 }, { 0.645828,-0.430376,0.630621 }, { 0.246619,0.14398,-0.958357 }, { -0.685881,0.525769,-0.503125 }, { -0.517516,-0.0410977,-0.854686 }, { -0.463013,-0.843602,0.271945 }, { -0.0415956,-0.991296,-0.12491 }, { 0.141675,0.970587,0.194653 }, { -0.271737,-0.923429,0.270993 }, { 0.531673,-0.0892442,-0.842234 }, { -0.987587,0.141071,-0.0690721 }, { -0.184506,-0.905782,-0.381467 }, { 0.843001,0.453146,0.289841 }, { 0.598284,0.764946,0.238565 }, { 0.977912,-0.137928,-0.157046 }, { 0.621748,-0.74933,0.22789 }, { -0.780795,-0.588364,0.210208 }, { -0.220848,-0.769464,-0.599292 }, { 0.855617,-0.251997,0.452125 }, { 0.917424,-0.342008,0.203382 }, { 0.441082,0.579448,0.685337 }, { -0.509043,0.0885631,-0.856173 }, { 0.560355,-0.656842,-0.50454 }, { 0.548192,0.571686,-0.610459 }, { -0.716893,-0.417658,0.558235 }, { 0.464637,-0.885467,0.00780453 }, { -0.703826,-0.6888,0.173734 }, { -0.78906,0.401402,0.465038 }, { 0.0156625,0.641766,0.766741 }, { 0.294053,0.866156,-0.404111 }, { -0.102477,-0.950015,-0.294906 }, { -0.337476,0.400548,-0.851863 }, { -0.183512,-0.166119,-0.96888 }, { -0.761709,0.630762,-0.148116 }, { 0.574923,0.602012,0.554117 }, { 0.203744,-0.853779,-0.479113 }, { -0.00798792,0.999737,0.0215005 }, { 0.677404,-0.391218,0.622955 }, { -0.815094,0.518173,0.25907 }, { 0.132827,-0.894498,0.426884 }, { -0.593387,-0.129533,0.794426 }, { -0.598621,-0.269058,-0.754494 }, { 0.50647,0.0429614,-0.861187 }, { 0.513761,-0.0873734,0.853473 }, { 0.866916,-0.466734,-0.174973 }, { -0.457191,0.831483,-0.315615 }, { -0.299509,0.734294,0.609186 }, { -0.127551,-0.199195,0.971623 }, { 0.0474361,0.740392,-0.6705 }, { 0.158845,-0.987133,0.0183756 }, { -0.286056,-0.45995,0.840606 }, { -0.56238,0.562325,-0.606233 }, { 0.675337,0.489026,-0.552063 }, { -0.962879,0.0183395,0.269311 }, { 0.594715,-0.226561,0.771352 }, { 0.763063,0.128532,0.633415 }, { -0.206158,0.339559,0.917714 }, { 0.859512,0.510172,-0.0310404 }, { -0.0660017,-0.0518204,0.996473 }, { -0.150708,-0.970199,0.189737 }, { 0.264597,-0.781519,0.564993 }, { -0.497814,0.572053,0.651871 }, { 0.501956,0.683997,-0.529328 }, { -0.282503,-0.950973,0.125865 }, { 0.1352,-0.988438,-0.06864 }, { -0.282702,0.638228,-0.716062 }, { -0.656422,0.0287193,-0.753847 }, { 0.208379,-0.908798,0.361475 }, { -0.449788,0.803432,0.390113 }, { 0.497612,-0.195281,0.845132 }, { 0.478706,-0.591182,0.64911 }, { 0.332439,0.65519,-0.678388 }, { -0.224547,0.931102,0.287451 }, { 0.866684,0.173673,0.46765 }, { -0.642039,0.527463,0.55639 }, { 0.821565,0.569369,0.0291539 }, { -0.0965395,0.227327,-0.969021 }, { 0.485838,0.08013,0.870368 }, { 0.41181,0.863865,-0.290087 }, { -0.877688,0.468305,0.101758 }, { 0.900076,-0.262106,-0.348086 }, { 0.350322,-0.595606,-0.722861 }, { -0.997071,0.0479511,-0.0595866 }, { -0.4779,0.47159,-0.74109 }, { 0.784974,-0.0653942,0.616068 }, { -0.942425,0.127952,-0.308971 }, { 0.488343,-0.775291,-0.400557 }, { 0.578381,-0.63869,0.507494 }, { 0.988325,-0.0779259,-0.130922 }, { 0.641157,-0.374007,-0.670102 }, { -0.228031,0.9065,0.35533 }, { -0.25019,-0.838703,-0.483718 }, { 0.0810177,-0.0996475,0.991719 }, { 0.318871,-0.816779,0.480825 }, { -0.527652,0.849221,0.0201835 }, { -0.413265,-0.86432,0.286641 }, { 0.262444,0.919294,-0.293294 }, { 0.0588558,0.511168,0.857463 }, { -0.488005,0.382953,0.784346 }, { 0.476994,-0.244857,-0.84411 }, { 0.299166,0.928119,-0.221575 }, { -0.173116,0.631585,0.755732 }, { 0.936239,0.296925,0.187862 }, { 0.28606,-0.621213,-0.729564 }, { -0.763401,0.584881,0.274105 }, { -0.349918,-0.209879,0.912966 }, { -0.895935,0.433536,0.0966801 }, { -0.6814,-0.670747,0.292904 }, { 0.136759,-0.79238,-0.594501 }, { 0.822134,0.562461,0.0879401 }, { 0.424749,0.683623,-0.593504 }, { -0.0747487,0.715274,0.694835 }, { -0.459191,-0.281188,-0.84266 }, { 0.320708,-0.316255,0.892821 }, { -0.000195973,0.968471,0.249128 }, { 0.977116,0.212104,-0.0160051 }, { -0.233741,0.0498687,0.971019 }, { -0.848421,-0.457529,0.266176 }, { 0.908748,0.240219,-0.341281 }, { 0.887017,0.384523,0.255621 }, { 0.56382,0.778539,0.275653 }, { 0.420234,0.869223,0.26049 }, { 0.82864,0.472263,-0.300539 }, { -0.180138,0.972185,-0.14969 }, { -0.46077,-0.161684,0.872668 }, { -0.461698,-0.774814,0.431854 }, { 0.378634,0.84215,-0.383953 }, { -0.150442,0.469605,0.869965 }, { 0.989448,0.0447963,-0.137789 }, { 0.525245,-0.588033,-0.61509 }, { -0.130293,-0.363557,0.922415 }, { 0.189538,0.277437,-0.941862 }, { 0.57935,0.799426,-0.158971 }, { -0.401727,-0.256848,0.879002 }, { -0.0267194,0.00601085,-0.999625 }, { 0.323036,0.025283,0.946049 }, { 0.575425,0.759032,0.30456 }, { 0.291424,-0.264203,-0.919385 }, { 0.749912,0.600642,-0.277238 }, { -0.103694,-0.458468,-0.88264 }, { 0.388725,-0.884519,0.257912 }, { 0.820942,0.205512,-0.532747 }, { 0.881102,0.373738,0.289793 }, { 0.646729,0.643122,0.410043 }, { -0.69647,-0.103343,0.710106 }, { -0.758958,0.593995,0.266743 }, { -0.806636,-0.438702,-0.396079 }, { -0.672382,0.689798,0.268479 }, { 0.238804,-0.916859,0.319911 }, { -0.336248,0.863687,0.375477 }, { 0.790803,0.156416,-0.591746 }, { -0.944496,-0.262094,0.198074 }, { 0.30435,0.534205,0.788667 }, { 0.890343,-0.286362,-0.353959 }, { -0.385709,-0.820423,-0.42206 }, { 0.274585,0.0339316,-0.960964 }, { -0.396699,-0.881564,-0.255881 }, { 0.25842,0.817563,-0.514596 }, { 0.547517,0.294833,0.783134 }, { 0.553166,-0.677312,-0.485031 }, { -0.858922,-0.472283,-0.197996 }, { -0.0951316,0.975694,-0.19741 }, { -0.299695,-0.17562,-0.937732 }, { -0.082973,-0.280427,0.956282 }, { -0.349532,-0.712517,-0.608397 }, { -0.136338,0.826922,-0.545538 }, { 0.654914,-0.521881,-0.546561 }, { -0.469828,-0.035166,-0.882057 }, { 0.0968897,-0.0902695,-0.991193 }, { -0.479792,-0.166208,-0.861495 }, { 0.733615,0.548993,-0.40052 }, { -0.801972,0.0949268,-0.589771 }, { 0.771141,0.00319058,0.636657 }, { 0.952318,0.206405,-0.224695 }, { -0.705452,0.105686,-0.700834 }, { 0.852339,0.117083,-0.509715 }, { -0.467995,0.821103,0.326758 }, { 0.157773,-0.619175,-0.76924 }, { 0.70127,0.120451,-0.702646 }, { -0.59492,0.801578,0.0595336 }, { 0.213569,-0.493667,0.843019 }, { -0.80494,0.56206,-0.190162 }, { -0.171186,0.93397,-0.31368 }, { -0.299164,0.370468,0.879349 }, { 0.493235,-0.611316,0.618879 }, { 0.581282,0.453523,0.675595 }, { 0.593582,-0.603139,0.532808 }, { -0.909646,-0.358179,-0.210362 }, { 0.559869,-0.662772,0.497272 }, { -0.191802,0.608544,-0.769991 }, { 0.346122,-0.661244,0.665549 }, { 0.0296552,-0.568236,0.822331 }, { 0.106132,0.228959,0.967633 }, { -0.201356,0.570967,-0.795897 }, { -0.568292,0.258763,-0.78108 }, { 0.424616,0.457506,0.781274 }, { 0.116078,0.951826,-0.28382 }, { -0.17797,-0.693,-0.698625 }, { -0.459185,0.886223,0.0613055 }, { 0.79617,-0.406076,0.448571 }, { 0.668499,0.0781926,-0.739591 }, { 0.556856,-0.563253,-0.610456 }, { 0.519684,-0.166455,0.837987 }, { -0.863063,-0.466105,0.1946 }, { -0.16052,-0.821449,-0.547224 }, { -0.417444,-0.571017,-0.70688 }, { -0.946456,0.0218126,0.322095 }, { -0.904627,-0.423336,0.0493581 }, { -0.483063,0.570092,0.664564 }, { -0.622769,-0.571464,-0.534405 }, { 0.548214,-0.526528,-0.649792 }, { -0.441506,0.748539,0.494734 }, { 0.207318,-0.789023,-0.578327 }, { 0.635082,0.680691,-0.365144 }, { 0.613279,-0.175911,0.770028 }, { -0.471549,-0.391471,-0.790184 }, { 0.72864,-0.107068,0.676477 }, { -0.760403,0.647205,0.0539718 }, { 0.760361,-0.0481715,-0.647712 }, { -0.507843,-0.837564,-0.201448 }, { -0.948893,0.266992,0.168279 }, { -0.598596,0.568604,0.564245 }, { 0.14618,0.399532,0.904989 }, { -0.456872,-0.720548,-0.521612 }, { 0.970891,-0.0635678,0.230931 }, { 0.0455778,-0.906543,0.419645 }, { 0.237166,0.836401,0.494152 }, { -0.260743,-0.50237,-0.824401 }, { 0.710043,-0.699867,0.077623 }, { -0.119726,0.968371,-0.218916 }, { -0.148946,-0.126901,-0.980669 }, { -0.275976,-0.90432,0.325643 }, { 0.999836,0.0179179,0.00249936 }, { -0.0939087,0.476906,0.873923 }, { -0.552733,-0.123589,-0.824143 }, { -0.0899534,0.0242877,-0.99565 }, { 0.447809,-0.237172,0.8621 }, { 0.843561,0.468681,-0.262189 }, { -0.464399,0.842563,-0.272803 }, { 0.498392,-0.847289,0.183595 }, { -0.0987671,-0.895783,-0.43338 }, { 0.173854,-0.607052,-0.775412 }, { -0.950333,0.256178,0.17675 }, { -0.808452,0.429147,-0.402787 }, { 0.502984,0.524146,0.687225 }, { -0.875911,0.430212,-0.218399 }, { -0.146586,-0.455835,-0.87791 }, { 0.97173,0.236009,-0.00644619 }, { 0.151193,0.913712,-0.377189 }, { -0.899286,0.3701,0.233045 }, { 0.0279291,-0.0191416,-0.999427 }, { -0.435525,0.142431,-0.888837 }, { 0.622442,0.57666,0.529178 }, { -0.976959,-0.10061,-0.188223 }, { 0.0619783,0.61406,-0.786822 }, { 0.603997,0.757401,-0.248053 }, { 0.686297,0.6924,-0.222665 }, { -0.149721,-0.879125,0.452463 }, { 0.379971,-0.0606177,0.92301 }, { 0.454909,0.855702,-0.246642 }, { -0.684408,-0.715119,-0.142089 }, { 0.0525315,-0.917494,0.394265 }, { -0.984874,0.0567441,0.163716 }, { -0.376207,0.151814,0.914013 }, { -0.889986,0.156507,0.428287 }, { 0.0508916,-0.896421,0.440271 }, { 0.506201,0.720106,0.474561 }, { 0.501288,0.621014,-0.602538 }, { -0.2944,0.809343,-0.508226 }, { -0.405052,0.759923,-0.50838 }, { 0.650178,-0.639888,-0.409649 }, { 0.901284,-0.423666,-0.0905246 }, { -0.507972,0.59907,-0.618934 }, { 0.455528,0.639878,0.61891 }, { 0.230438,0.551193,0.801925 }, { 0.957581,-0.266892,-0.108663 }, { 0.918439,0.0733391,-0.388704 }, { 0.307095,0.791491,-0.528427 }, { 0.794804,0.183304,0.57852 }, { 0.989584,-0.141784,0.0248985 }, { 0.619738,-0.4881,-0.61456 }, { 0.583091,0.807627,0.0879972 }, { -0.0690386,-0.895815,-0.439031 }, { -0.242681,0.934781,-0.259406 }, { -0.917228,0.390375,-0.0793688 }, { 0.694195,0.713333,0.0961687 }, { 0.204567,0.962897,0.176014 }, { 0.828472,0.302584,0.471251 }, { 0.0296131,0.253033,0.967004 }, { 0.859933,0.48926,0.145392 }, { -0.833025,-0.361335,-0.418936 }, { 0.365287,-0.907075,0.209237 }, { 0.201145,-0.508213,-0.837413 }, { 0.753093,-0.656592,0.0416842 }, { -0.486135,-0.807979,0.332931 }, { 0.501133,-0.272682,-0.821286 }, { -0.62141,0.781765,0.0518952 }, { 0.243171,0.969678,0.024363 }, { 0.945886,-0.278053,0.16729 }, { -0.0738451,-0.63738,-0.767003 }, { -0.419787,-0.822015,0.3848 }, { 0.725214,-0.238596,-0.645862 }, { -0.201633,-0.847229,0.491475 }, { 0.688976,-0.335423,-0.642497 }, { -0.246371,-0.944698,0.21644 }, { 0.543639,-0.723366,0.425675 }, { -0.697446,0.00653605,0.716608 }, { -0.645581,0.747664,0.155641 }, { 0.949682,0.304888,-0.0717503 }, { 0.249783,0.939622,-0.23392 }, { 0.970653,-0.221527,0.0935835 }, { -0.338931,0.940166,0.0348405 }, { 0.428616,-0.128976,-0.894234 }, { -0.367967,-0.726511,0.58033 }, { -0.141686,-0.955461,-0.258879 }, { -0.0107806,-0.809322,-0.587266 }, { -0.877523,-0.193574,-0.438729 }, { -0.609099,-0.720587,-0.33129 }, { -0.0232971,-0.252623,-0.967284 }, { 0.852832,-0.416386,0.315118 }, { -0.344191,-0.658291,0.669467 }, { -0.858067,0.155823,-0.489325 }, { 0.802994,0.505072,0.316391 }, { 0.110778,-0.945985,-0.304697 }, { -0.0391144,-0.607158,0.793618 }, { 0.323963,-0.841397,0.432549 }, { -0.930926,-0.124756,0.343238 }, { 0.978689,0.131815,-0.157456 }, { 0.695575,-0.143798,-0.703916 }, { -0.372518,-0.466024,0.802529 }, { 0.427081,0.116699,-0.896651 }, { 0.692346,0.686081,-0.223497 }, { -0.304053,-0.483534,0.82082 }, { 0.110963,-0.483387,0.868346 }, { -0.375088,-0.461682,0.80384 }, { 0.410617,-0.43438,-0.801691 }, { -0.695892,0.710809,-0.102398 }, { 0.520786,0.822262,-0.229494 }, { 0.78752,0.613848,0.0547962 }, { 0.618469,0.75722,0.210032 }, { 0.363268,-0.47695,-0.800347 }, { -0.353503,0.106097,0.929397 }, { -0.666994,0.524525,-0.529143 }, { -0.370041,-0.486017,0.791743 }, { -0.0670981,0.839184,-0.539692 }, { 0.477306,-0.793401,0.377748 }, { -0.807242,0.499964,-0.313681 }, { -0.380399,-0.557359,-0.738003 }, { -0.855753,-0.490483,0.164658 }, { -0.449445,0.214864,-0.867083 }, { 0.987052,0.0736918,0.142474 }, { -0.213384,-0.934849,0.283768 }, { 0.402001,0.202042,-0.89307 }, { -0.350328,0.863154,-0.363643 }, { 0.881308,0.389735,0.267212 }, { 0.810928,-0.539939,-0.225527 }, { -0.803882,0.402813,-0.437626 }, { 0.983178,0.0712831,-0.168164 }, { -0.313511,0.939613,-0.137249 }, { -0.0557558,0.501843,0.86316 }, { -0.2634,-0.963346,-0.0508317 }, { -0.887735,0.0502856,-0.457601 }, { 0.779631,0.0178821,-0.625983 }, { 0.721641,0.204139,-0.661485 }, { 0.175877,-0.00460269,-0.984401 }, { -0.391104,0.308647,-0.867049 }, { 0.173799,0.967745,-0.182381 }, { -0.472131,-0.870518,0.138888 }, { 0.892767,-0.174763,-0.415241 }, { 0.712375,-0.267541,-0.648801 }, { 0.947792,0.182506,-0.261501 }, { 0.32635,-0.909717,0.25673 }, { 0.0693152,-0.939587,0.335218 }, { -0.134613,0.966851,0.216978 }, { -0.50317,0.340791,-0.794155 }, { -0.884992,0.224023,0.408169 }, { 0.947992,0.124217,-0.293054 }, { -0.081123,0.778613,0.622239 }, { -0.127847,-0.898602,0.419725 }, { -0.985676,-0.163408,-0.0417263 }, { 0.4092,-0.701664,-0.583287 }, { 0.727839,0.244067,0.640845 }, { 0.668931,0.680546,-0.29898 }, { 0.396423,-0.76781,0.503306 }, { -0.424051,0.442895,0.789952 }, { 0.886967,-0.158771,0.433683 }, { 0.702261,0.357071,-0.615897 }, { -0.115958,0.0763258,0.990317 }, { -0.43564,0.649936,-0.622737 }, { 0.745873,-0.625853,0.227994 }, { -0.142665,0.984954,-0.0975289 }, { 0.680993,0.500709,-0.534359 }, { -0.999546,0.0287624,-0.00896164 }, { 0.768709,-0.622251,0.147956 }, { -0.725784,-0.146529,-0.672136 }, { 0.301031,-0.945686,-0.122711 }, { 0.852468,-0.411946,-0.321867 }, { 0.855166,0.249652,0.454273 }, { 0.486952,0.545704,0.681971 }, { 0.932612,-0.249845,-0.260407 }, { -0.551691,-0.620289,-0.557565 }, { 0.451647,0.0561142,-0.89043 }, { 0.614931,0.740299,0.271693 }, { -0.525863,-0.194253,0.82809 }, { -0.760929,-0.501261,0.411976 }, { -0.582082,-0.758714,0.292462 }, { 0.154958,0.190881,-0.969305 }, { 0.0232719,0.692175,0.721354 }, { 0.0825491,0.813035,0.576333 }, { -0.5135,-0.813996,0.27153 }, { 0.114456,-0.829863,-0.546102 }, { -0.350331,0.874281,-0.336009 }, { 0.52785,0.840282,0.123692 }, { 0.354486,-0.924629,-0.13929 }, { -0.037307,0.673782,-0.737987 }, { 0.390652,0.803224,0.449692 }, { 0.801516,0.438856,0.406175 }, { -0.894495,-0.389973,-0.218633 }, { 0.977503,0.210274,0.0165066 }, { -0.75249,-0.575843,-0.31963 }, { 0.725406,-0.681157,0.0990522 }, { 0.412564,-0.755349,-0.509156 }, { -0.234163,-0.813563,-0.532243 }, { 0.28455,-0.158259,0.945508 }, { 0.0626414,-0.85841,-0.509125 }, { 0.496891,0.742036,0.44998 }, { 0.301236,-0.291962,-0.907753 }, { 0.507325,0.634316,0.583322 }, { -0.387737,0.920932,-0.0393046 }, { -0.0611886,-0.963813,0.259462 }, { 0.677932,0.690938,-0.251025 }, { 0.0513202,0.910732,-0.409797 }, { -0.298788,-0.275131,-0.913799 }, { 0.505485,0.0569992,0.860951 }, { 0.949484,-0.171012,-0.263125 }, { -0.906638,-0.40222,-0.127382 }, { -0.333593,0.218367,0.917078 }, { 0.27637,-0.954606,-0.111118 }, { -0.553207,-0.494902,-0.6701 }, { 0.685672,-0.724434,-0.071067 }, { -0.551433,0.597155,0.582518 }, { 0.410658,-0.820487,0.397695 }, { -0.317241,-0.946822,0.0537258 }, { 0.0606055,-0.683621,0.727316 }, { -0.950178,0.0585999,0.306151 }, { 0.174238,0.466967,-0.866939 }, { -0.134634,-0.953982,-0.267942 }, { -0.167232,0.148768,0.974629 }, { -0.294208,0.895803,0.333135 }, { -0.529987,0.823075,-0.204111 }, { 0.507014,-0.857818,-0.0841682 }, { 0.853806,0.0117971,-0.520457 }, { -0.268263,-0.0512478,0.961982 }, { -0.267144,-0.807539,-0.525847 }, { 0.0118146,0.874617,0.48467 }, { 0.528361,0.443575,-0.723931 }, { 0.590126,0.399522,-0.701523 }, { 0.577253,0.42028,0.700103 }, { 0.279723,0.663015,-0.694382 }, { 0.347782,0.370998,-0.861051 }, { 0.81373,0.57449,-0.0883443 }, { 0.836385,0.127041,-0.533217 }, { -0.695169,-0.0451934,-0.717425 }, { -0.540466,0.384566,0.748335 }, { -0.509764,0.321001,-0.798185 }, { 0.181449,-0.983388,-0.00491665 }, { 0.476414,-0.825021,0.303925 }, { -0.212088,0.758226,0.616532 }, { 0.357677,-0.919317,-0.164083 }, { -0.524163,0.829261,0.193852 }, { -0.22633,-0.912899,-0.339692 }, { -0.689936,-0.692346,0.211295 }, { -0.02498,-0.998828,0.0414504 }, { -0.00515593,-0.485598,0.874167 }, { -0.0280924,0.985716,-0.166059 }, { -0.82874,0.559299,-0.0193684 }, { 0.227957,-0.361005,-0.904274 }, { 0.190976,-0.703633,0.684419 }, { -0.0533315,-0.883549,0.465292 }, { -0.341919,0.525239,-0.779241 }, { -0.561624,0.272391,-0.781269 }, { -0.316527,0.717616,-0.620353 }, { -0.473525,-0.850445,0.229167 }, { 0.804116,0.507518,0.309552 }, { -0.12823,0.751033,-0.647693 }, { 0.981462,0.146427,0.123657 }, { 0.485328,0.543513,-0.684872 }, { 0.652835,-0.201061,0.73033 }, { -0.728664,-0.474944,-0.493434 }, { 0.733791,0.105461,0.67114 }, { 0.170424,-0.800409,0.574718 }, { 0.533732,0.100186,-0.839698 }, { -0.80571,0.116569,-0.580726 }, { 0.199806,-0.86189,0.466072 }, { -0.388735,0.702065,-0.596649 }, { 0.0824684,-0.80804,0.583327 }, { -0.952445,-0.297644,-0.0652421 }, { 0.342221,-0.796293,-0.498801 }, { 0.89842,-0.354406,0.259302 }, { 0.277112,-0.818347,-0.503504 }, { -0.450827,-0.860188,0.238394 }, { 0.326695,0.00579992,-0.945112 }, { -0.119248,0.786188,-0.606373 }, { 0.750576,0.658761,-0.0516659 }, { 0.317619,-0.333866,0.887497 }, { 0.38093,0.303993,0.873201 }, { 0.838676,-0.50316,-0.208453 }, { 0.0918522,-0.359614,-0.928569 }, { 0.0770786,-0.996018,0.0447966 }, { 0.0869882,0.28308,0.955143 }, { -0.235315,-0.661291,-0.712265 }, { 0.641471,0.720919,0.262278 }, { -0.870962,-0.463816,0.16217 }, { -0.706673,0.695876,-0.127949 }, { 0.902691,0.3123,-0.296004 }, { -0.496664,0.0985662,0.862328 }, { -0.794812,0.483741,0.366428 }, { -0.627241,-0.488068,-0.606925 }, { -0.577202,-0.0462201,0.815292 }, { -0.65584,0.754899,-0.000886882 }, { 0.0648057,0.123395,-0.990239 }, { -0.620726,0.165652,-0.766328 }, { -0.0162012,-0.0317439,0.999365 }, { 0.543344,0.745653,0.385718 }, { 0.555161,-0.476917,-0.68143 }, { 0.385476,-0.38891,0.836754 }, { 0.991037,0.0265679,-0.130918 }, { -0.226737,-0.952803,-0.201883 }, { -0.509995,0.779489,0.363733 }, { 0.127385,-0.547623,-0.826972 }, { -0.443689,-0.602572,0.66336 }, { -0.305934,-0.668805,0.677573 }, { 0.767099,0.641494,0.00668347 }, { -0.167729,0.0827473,-0.982354 }, { 0.240104,-0.966031,0.0955721 }, { 0.265511,0.287718,0.920175 }, { 0.17211,-0.190523,-0.966478 }, { -0.749349,-0.631084,-0.200524 }, { -0.0839644,-0.7029,-0.706316 }, { -0.846688,0.428738,-0.315124 }, { -0.582476,0.748204,0.317668 }, { 0.132445,0.890966,0.434325 }, { 0.0422852,-0.606583,-0.793895 }, { -0.891776,0.0801057,-0.445329 }, { -0.169034,-0.251967,0.952859 }, { -0.880026,-0.439568,-0.179817 }, { 0.204542,-0.597438,-0.775391 }, { 0.534385,0.787107,0.308051 }, { 0.546123,0.34151,0.764932 }, { 0.251391,-0.963661,0.0903392 }, { -0.236755,0.418064,-0.877023 }, { -0.599523,0.411853,-0.686257 }, { 0.859044,-0.129168,0.495337 }, { -0.045998,0.118155,-0.991929 }, { 0.512858,-0.718741,0.469455 }, { 0.7516,0.623059,-0.216554 }, { 0.710471,0.39301,-0.583758 }, { 0.620056,-0.782698,0.0539844 }, { 0.409139,0.481193,0.77528 }, { -0.0245102,0.763395,0.645467 }, { -0.617738,-0.786136,0.0197439 }, { 0.291845,0.952936,-0.0821005 }, { -0.229211,0.296339,-0.927171 }, { -0.969165,-0.237308,-0.0663659 }, { 0.44145,-0.481374,-0.757232 }, { -0.187159,-0.331969,0.924537 }, { -0.961305,0.272517,-0.040332 }, { 0.10673,-0.993094,-0.0487087 }, { -0.306204,0.767519,-0.563164 }, { -0.0416648,0.161502,-0.985993 }, { -0.757445,0.286696,0.586585 }, { -0.215819,0.0147139,0.976322 }, { 0.33691,0.18853,0.922468 }, { 0.998583,0.0222833,-0.0483307 }, { 0.961765,0.161074,-0.221502 }, { 0.294182,-0.284631,0.912383 }, { -0.664656,-0.231643,0.710334 }, { -0.544217,0.234206,0.80559 }, { -0.423324,-0.538315,0.728707 }, { -0.565213,-0.788506,-0.242471 }, { -0.213138,-0.894246,0.393568 }, { -0.130494,-0.751839,-0.646305 }, { 0.958268,0.239876,-0.155505 }, { 0.290058,-0.823204,0.488058 }, { 0.309625,0.928692,-0.204118 }, { 0.285388,0.209678,-0.935195 }, { 0.624958,0.774744,-0.095911 }, { -0.720927,-0.673241,0.164351 }, { 0.200143,0.582396,0.787882 }, { 0.709433,0.70174,-0.0653112 }, { 0.669754,-0.142254,0.72883 }, { -0.599268,0.426455,-0.677506 }, { -0.642151,-0.532336,0.551598 }, { -0.189632,-0.824074,0.5338 }, { 0.562871,0.188189,-0.804836 }, { 0.149933,-0.619419,-0.77061 }, { 0.336407,0.767599,-0.545547 }, { -0.517906,0.850619,0.0906704 }, { -0.414094,0.398082,0.81857 }, { -0.516187,0.645454,0.562974 }, { -0.524015,0.109885,-0.844591 }, { -0.368867,0.162392,-0.915186 }, { -0.485972,0.498977,-0.717532 }, { 0.886963,-0.272953,0.372551 }, { -0.605056,-0.366342,0.706895 }, { 0.169401,-0.695185,0.698585 }, { 0.0332623,-0.781223,0.623366 }, { 0.921565,-0.208774,0.327311 }, { -0.716401,0.169703,-0.676735 }, { 0.795758,-0.565624,0.216424 }, { -0.823709,0.296251,-0.483465 }, { 0.775355,-0.631177,-0.0209815 }, { 0.853316,-0.521369,0.00515418 }, { 0.868899,0.493962,0.0318651 }, { -0.863028,-0.41403,0.289417 }, { -0.694045,-0.454706,0.558162 }, { 0.823619,0.156086,0.545242 }, { -0.483097,-0.547453,0.68331 }, { -0.717736,0.513161,-0.470659 }, { -0.602728,-0.79768,0.020636 }, { -0.0745711,0.799712,0.595734 }, { -0.796636,-0.604176,-0.0185038 }, { -0.624775,0.62701,0.465311 }, { 0.746128,-0.215432,-0.629985 }, { 0.583907,-0.694087,-0.421066 }, { -0.249173,-0.530496,0.810239 }, { 0.447868,-0.404453,0.797391 }, { -0.601912,0.70342,-0.378024 }, { 0.503597,-0.7666,-0.39839 }, { -0.0432977,-0.917327,0.395773 }, { 0.561908,0.827107,-0.0124098 }, { 0.274627,-0.773509,-0.571195 }, { -0.100463,0.984973,0.140485 }, { -0.306033,-0.373382,0.875745 }, { -0.189793,0.347416,-0.918303 }, { 0.684423,-0.358441,-0.63489 }, { 0.154625,-0.410088,-0.898843 }, { 0.0837662,0.979523,-0.183079 }, { 0.983055,0.0927441,0.158117 }, { 0.377514,-0.0897554,-0.921644 }, { 0.474456,-0.785498,0.397348 }, { 0.946791,0.17966,0.267038 }, { -0.372675,-0.635225,-0.676464 }, { -0.762694,-0.645571,0.0391895 }, { 0.472626,0.369202,-0.800197 }, { -0.212122,0.521412,-0.826519 }, { -0.669931,0.549606,0.499126 }, { 0.756469,-0.142304,0.638361 }, { 0.473611,-0.338072,0.813265 }, { 0.395505,-0.243256,0.885665 }, { 0.0776741,0.971174,-0.225362 }, { -0.885607,0.446235,-0.128746 }, { -0.210676,-0.0709873,-0.974975 }, { -0.462695,-0.854613,-0.235689 }, { -0.592331,0.746312,-0.303583 }, { -0.425337,0.904805,-0.0203828 }, { 0.608561,0.525098,0.594917 }, { 0.0649888,0.996097,0.0597284 }, { -0.362816,-0.269801,0.891949 }, { -0.766185,0.621968,-0.161605 }, { 0.939575,-0.332882,-0.0799323 }, { -0.599137,0.617999,0.50903 }, { -0.969796,-0.117412,-0.213801 }, { 0.754161,-0.64183,-0.138905 }, { -0.334144,0.0590088,0.940673 }, { 0.525938,-0.250542,-0.812784 }, { -0.712644,-0.427926,-0.555894 }, { -0.403908,-0.690779,0.599735 }, { 0.144041,-0.270566,-0.951864 }, { -0.0660092,-0.876307,-0.477209 }, { 0.104023,-0.181341,-0.977903 }, { 0.48906,-0.821429,-0.293384 }, { 0.959549,-0.169572,0.224747 }, { -0.795625,0.301403,0.525487 }, { -0.575123,0.565714,-0.590933 }, { 0.113588,-0.989182,0.0928245 }, { -0.554664,-0.362418,-0.749 }, { 0.437753,0.898232,-0.039403 }, { 0.647599,0.0590156,0.759693 }, { 0.406042,0.644981,-0.647403 }, { 0.728992,0.129812,-0.672101 }, { 0.397173,0.895858,-0.199226 }, { -0.582126,-0.736476,0.344575 }, { -0.359194,0.89073,0.278532 }, { 0.348287,0.833668,-0.428596 }, { -0.90668,0.35291,0.231055 }, { -0.498184,-0.67272,-0.547047 }, { -0.518101,0.854275,-0.0422483 }, { 0.00640995,0.436793,0.899539 }, { 0.694356,-0.462493,-0.551335 }, { 0.585998,-0.0415081,0.809249 }, { 0.229142,-0.522038,-0.821566 }, { 0.505374,0.576399,0.642154 }, { -0.881574,0.364751,0.299639 }, { 0.0787948,-0.940785,-0.32972 }, { 0.231267,0.886991,0.399704 }, { 0.246038,-0.967404,-0.0599558 }, { 0.976604,0.156829,-0.147137 }, { -0.175935,-0.887357,-0.426197 }, { -0.0888067,0.814826,-0.572863 }, { -0.504073,0.780714,-0.369319 }, { 0.427769,-0.733496,-0.528203 }, { -0.726317,0.686261,-0.0388486 }, { 0.179081,-0.588791,0.788197 }, { -0.394133,-0.853582,-0.340671 }, { 0.78888,-0.377468,-0.48496 }, { -0.0520013,-0.383562,-0.92205 }, { -0.893324,0.0747461,0.443153 }, { -0.947471,-0.267776,-0.174912 }, { 0.372373,0.16703,0.912929 }, { 0.576746,-0.185424,0.795601 }, { -0.209963,0.825562,0.523797 }, { 0.531386,-0.847062,0.0106966 }, { 0.660144,0.407805,0.630797 }, { 0.732455,-0.363599,0.575592 }, { 0.291914,-0.825468,0.483104 }, { -0.439027,0.722985,0.53343 }, { -0.594867,0.790935,0.143369 }, { 0.145116,0.925241,0.350529 }, { 0.832664,-0.0850836,-0.547203 }, { -0.138171,0.773721,0.618276 }, { -0.43245,-0.753266,-0.495558 }, { 0.675908,-0.661027,-0.32587 }, { 0.0922018,-0.326303,-0.940758 }, { 0.854707,-0.515165,-0.063882 }, { 0.352314,0.562006,-0.748348 }, { -0.257888,0.827191,0.499248 }, { -0.238609,-0.950512,-0.198981 }, { 0.467982,-0.33159,-0.819171 }, { 0.316668,-0.789939,0.525088 }, { 0.552343,0.707906,0.440211 }, { -0.25786,0.758563,-0.598407 }, { 0.980166,0.131264,0.148473 }, { -0.079118,-0.976546,0.200246 }, { 0.987954,0.014368,0.154078 }, { 0.408421,0.813886,0.413256 }, { 0.752302,0.657332,0.0442238 }, { -0.463284,-0.769919,0.438854 }, { 0.568243,0.0029728,-0.822855 }, { 0.031022,-0.130467,0.990967 }, { 0.990519,-0.0387556,-0.131794 }, { 0.994624,0.0889935,-0.0529504 }, { 0.741371,-0.564076,0.363576 }, { -0.666811,0.0515178,0.743444 }, { -0.179059,0.431022,0.884397 }, { -0.116988,0.454373,0.883096 }, { -0.856769,0.392163,0.334895 }, { 0.0544791,-0.336532,-0.940095 }, { -0.576917,0.163969,-0.800176 }, { -0.753161,0.657624,0.0167232 }, { -0.732521,-0.00145441,-0.680743 }, { 0.68194,-0.730721,-0.0317004 }, { -0.59717,-0.10676,0.794978 }, { 0.815561,-0.551797,0.174299 }, { -0.0578817,-0.57246,-0.817887 }, { -0.539934,0.835346,-0.103292 }, { -0.946983,-0.11916,0.298369 }, { -0.462059,-0.739832,0.48903 }, { 0.136157,-0.758952,0.636752 }, { 0.634623,-0.217618,-0.741549 }, { -0.665494,0.0943016,0.740422 }, { -0.921073,0.134383,0.365466 }, { -0.294704,-0.226159,-0.92844 }, { 0.427131,-0.494603,-0.756919 }, { -0.258123,-0.177861,-0.949599 }, { 0.814817,-0.184763,0.549487 }, { -0.56051,-0.76659,0.313319 }, { 0.0280009,-0.996343,-0.0807278 }, { 0.0150423,-0.648973,0.760663 }, { 0.717395,-0.399097,0.571022 }, { -0.477909,-0.0825125,-0.874526 }, { 0.803847,-0.468609,-0.366382 }, { 0.284638,-0.350154,0.892397 }, { -0.538295,-0.811046,0.229005 }, { 0.969519,-0.0947611,-0.225949 }, { -0.248168,-0.959276,-0.134912 }, { -0.97322,0.227646,-0.0319455 }, { -0.923528,-0.376292,-0.0741714 }, { -0.0776691,0.348394,-0.934125 }, { -0.633594,0.57028,0.522819 }, { -0.647006,0.747056,0.152613 }, { -0.379962,-0.856087,0.350349 }, { -0.530126,-0.740667,0.41277 }, { 0.692724,-0.31589,0.648342 }, { 0.443442,-0.807031,0.38995 }, { -0.61987,-0.217277,-0.754024 }, { 0.155454,-0.779508,-0.606796 }, { -0.446471,0.196781,-0.872892 }, { 0.465126,-0.875732,0.129422 }, { -0.474305,-0.860205,-0.187301 }, { -0.266405,-0.809338,0.523451 }, { -0.483479,-0.822591,0.299321 }, { -0.526938,0.778557,-0.340861 }, { 0.0264823,0.599695,-0.79979 }, { -0.221466,-0.844942,-0.486854 }, { -0.80323,-0.0665852,0.591935 }, { -0.940704,0.332401,0.0677124 }, { 0.730779,0.419274,-0.538676 }, { 0.642794,0.0477978,0.764546 }, { 0.506012,0.819022,-0.270472 }, { 0.130599,-0.862353,0.489173 }, { 0.75464,0.548181,0.360579 }, { -0.884918,-0.403512,0.232589 }, { 0.405047,0.656485,-0.636368 }, { -0.866232,-0.0349065,0.498421 }, { -0.583675,-0.811932,-0.00947614 }, { 0.800791,-0.594164,-0.0755191 }, { 0.332112,-0.913002,-0.236915 }, { -0.0153234,-0.648054,-0.76144 }, { 0.587377,-0.547668,0.595859 }, { 0.89209,-0.184112,-0.412648 }, { -0.0953723,0.941601,-0.322941 }, { 0.622127,0.763271,-0.174286 }, { 0.909725,0.380148,0.166996 }, { -0.610757,0.67078,-0.42075 }, { -0.954538,-0.296097,-0.0344094 }, { 0.422611,0.692227,0.584997 }, { 0.108521,-0.117612,-0.987112 }, { 0.903547,-0.195479,0.381301 }, { -0.547486,0.584017,0.599319 }, { 0.707394,-0.0437245,0.705466 }, { 0.10611,-0.849294,-0.517146 }, { 0.333394,-0.816065,-0.472108 }, { 0.575538,0.810974,0.105254 }, { 0.558157,-0.683741,0.470063 }, { 0.260697,-0.846188,0.464761 }, { 0.315701,-0.492848,-0.810823 }, { 0.0823766,-0.985902,-0.145641 }, { -0.296834,0.832358,-0.468048 }, { 0.851573,-0.089689,0.516506 }, { -0.940818,-0.2806,-0.190067 }, { -0.0330614,-0.975659,0.216787 }, { -0.716925,0.486958,0.498889 }, { -0.749758,0.0749932,-0.657449 }, { 0.482694,0.792281,0.373226 }, { 0.708469,0.00198965,0.705739 }, { 0.754776,-0.311541,-0.577283 }, { -0.687044,0.713631,-0.136756 }, { 0.233785,0.956785,0.172934 }, { -0.240008,-0.857947,0.454229 }, { 0.542987,0.40361,0.736386 }, { 0.0326531,0.80638,0.590495 }, { -0.333953,0.560826,0.757594 }, { -0.870133,0.368684,-0.327017 }, { 0.745522,-0.612346,-0.263115 }, { 0.953437,-0.0887491,-0.288239 }, { -0.460043,0.5645,-0.685346 }, { -0.836416,-0.54568,0.0513966 }, { 0.647267,-0.507912,0.568393 }, { -0.742267,0.603927,-0.290365 }, { -0.625443,0.434792,0.647902 }, { 0.633467,0.101981,0.76702 }, { 0.615992,-0.0507071,-0.786119 }, { 0.579906,-0.607729,0.542563 }, { 0.21613,-0.670424,-0.709803 }, { -0.395525,-0.884995,-0.24565 }, { 0.0594872,-0.52731,-0.847588 }, { 0.596391,0.707488,-0.379182 }, { -0.12898,-0.543596,-0.829378 }, { 0.681881,-0.532843,0.501115 }, { -0.0256417,0.830853,-0.5559 }, { 0.78813,0.612637,-0.0593883 }, { 0.835888,0.115652,-0.536578 }, { 0.732543,0.418795,-0.536648 }, { 0.977152,0.209706,0.0346145 }, { 0.807478,0.523963,0.271003 }, { -0.493483,-0.330146,0.80466 }, { -0.916436,-0.0281943,-0.399187 }, { 0.592034,-0.542728,-0.59577 }, { -0.261623,0.569832,0.779003 }, { -0.984448,0.149187,-0.0927637 }, { -0.557732,0.0782083,-0.826328 }, { -0.930305,-0.263576,0.255067 }, { -0.903932,0.422906,0.0637004 }, { 0.738728,0.527805,-0.419169 }, { 0.699243,0.249067,-0.670093 }, { -0.692693,-0.0640905,-0.718379 }, { -0.333047,0.227656,0.915015 }, { -0.0416427,0.85795,0.512042 }, { 0.044029,0.242582,-0.969131 }, { -0.343728,0.587913,0.732263 }, { 0.873094,0.451017,0.185178 }, { 0.376186,-0.913598,0.154345 }, { -0.500946,-0.10413,0.859192 }, { -0.168621,-0.890865,-0.421813 }, { -0.119882,-0.649205,0.751107 }, { -0.570847,-0.572209,0.588822 }, { 0.430715,0.724131,0.538627 }, { -0.788098,0.615472,-0.00982647 }, { -0.333001,-0.441249,0.833313 }, { -0.612826,0.502349,-0.609992 }, { 0.392413,0.85833,0.330577 }, { 0.222624,0.136578,-0.96529 }, { -0.987197,-0.0445472,-0.153159 }, { 0.147161,-0.728027,-0.669567 }, { 0.896797,-0.41804,0.144904 }, { -0.984821,0.146624,-0.0928957 }, { -0.552727,0.406119,-0.727709 }, { -0.403452,0.782982,0.473461 }, { 0.240594,-0.848096,0.472068 }, { 0.328828,0.942943,-0.0522498 }, { -0.204184,-0.646776,0.73484 }, { -0.88256,-0.373287,0.28591 }, { -0.645072,-0.0871545,0.759135 }, { -0.613952,0.735791,-0.285788 }, { 0.0290869,-0.982086,-0.186176 }, { -0.91248,0.299189,-0.279047 }, { -0.538195,0.400479,0.741595 }, { 0.414685,0.833155,-0.365907 }, { -0.174274,0.251532,-0.95203 }, { 0.138118,0.862283,0.487229 }, { 0.654917,-0.717876,0.23609 }, { 0.853545,0.0557131,-0.518032 }, { 0.628672,0.255758,-0.734411 }, { -0.631019,-0.476601,-0.6121 }, { 0.380818,0.924611,-0.00849564 }, { 0.830112,-0.0229129,-0.557126 }, { -0.874545,0.141151,-0.463948 }, { 0.233492,0.961521,0.144772 }, { -0.731113,0.0668069,0.678978 }, { -0.586998,0.56462,-0.580205 }, { 0.0477931,-0.719618,0.692724 }, { 0.0676299,0.767856,-0.637042 }, { 0.735073,0.130282,-0.665353 }, { 0.505459,0.513592,0.69335 }, { 0.515906,0.849061,-0.11374 }, { 0.424736,-0.525125,0.737457 }, { 0.782778,-0.224021,-0.580581 }, { -0.0667832,-0.55466,-0.829393 }, { 0.583925,0.766327,-0.267906 }, { -0.604931,0.746517,-0.277074 }, { -0.742788,-0.235251,-0.626836 }, { -0.400067,0.762207,0.508907 }, { -0.00426167,0.998549,0.0536775 }, { -0.785582,-0.121026,0.606806 }, { -0.404355,-0.913951,0.0345121 }, { -0.88368,0.382322,-0.270073 }, { 0.881222,0.115711,-0.458321 }, { -0.701469,0.630814,0.331685 }, { -0.562963,0.72398,0.398655 }, { 0.408996,-0.515596,0.752916 }, { -0.462667,0.769015,-0.441083 }, { -0.579102,-0.777961,0.243757 }, { 0.486669,0.318986,-0.813266 }, { -0.770777,0.575567,-0.273177 }, { 0.660334,-0.105042,-0.74359 }, { -0.660321,0.0964276,0.744767 }, { 0.0783261,0.919177,-0.385977 }, { -0.697285,-0.3691,0.614458 }, { -0.717755,-0.0418237,-0.695038 }, { -0.0947467,0.03777,-0.994785 }, { 0.182742,-0.675672,-0.714194 }, { -0.0131797,-0.491541,0.870755 }, { -0.702374,0.346641,-0.6217 }, { -0.149444,-0.904169,-0.400181 }, { 0.599306,0.634349,0.488297 }, { 0.578358,0.364206,0.729969 }, { 0.0657996,0.827075,-0.558227 }, { -0.121967,-0.264481,-0.956647 }, { 0.732262,0.615485,-0.291497 } }; unsigned char hvNoise::perm[512] = { 151,160,137,91,90,15, 131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23, 190, 6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33, 88,237,149,56,87,174,20,125,136,171,168, 68,175,74,165,71,134,139,48,27,166, 77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244, 102,143,54, 65,25,63,161, 1,216,80,73,209,76,132,187,208, 89,18,169,200,196, 135,130,116,188,159,86,164,100,109,198,173,186, 3,64,52,217,226,250,124,123, 5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42, 223,183,170,213,119,248,152, 2,44,154,163, 70,221,153,101,155,167, 43,172,9, 129,22,39,253, 19,98,108,110,79,113,224,232,178,185, 112,104,218,246,97,228, 251,34,242,193,238,210,144,12,191,179,162,241, 81,51,145,235,249,14,239,107, 49,192,214, 31,181,199,106,157,184, 84,204,176,115,121,50,45,127, 4,150,254, 138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180, 151,160,137,91,90,15, 131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23, 190, 6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33, 88,237,149,56,87,174,20,125,136,171,168, 68,175,74,165,71,134,139,48,27,166, 77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244, 102,143,54, 65,25,63,161, 1,216,80,73,209,76,132,187,208, 89,18,169,200,196, 135,130,116,188,159,86,164,100,109,198,173,186, 3,64,52,217,226,250,124,123, 5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42, 223,183,170,213,119,248,152, 2,44,154,163, 70,221,153,101,155,167, 43,172,9, 129,22,39,253, 19,98,108,110,79,113,224,232,178,185, 112,104,218,246,97,228, 251,34,242,193,238,210,144,12,191,179,162,241, 81,51,145,235,249,14,239,107, 49,192,214, 31,181,199,106,157,184, 84,204,176,115,121,50,45,127, 4,150,254, 138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180 };
54,146
C++
.cpp
471
113.012739
177
0.622668
ASTex-ICube/semiproctex
39
8
2
LGPL-2.1
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,900
PtNoise.cpp
ASTex-ICube_semiproctex/PPTBF_Structures_Src/PtModel/PtNoise.cpp
/* * Publication: Semi-Procedural Textures Using Point Process Texture Basis Functions * Authors: anonymous * * Code author: Pascal Guehl * * anonymous * anonymous */ /** * @version 1.0 */ #include "PtNoise.h" /****************************************************************************** ******************************* INCLUDE SECTION ****************************** ******************************************************************************/ // STL #include <fstream> #include <iostream> #include <algorithm> #include <set> /****************************************************************************** ****************************** NAMESPACE SECTION ***************************** ******************************************************************************/ // Project using namespace Pt; /****************************************************************************** ************************* DEFINE AND CONSTANT SECTION ************************ ******************************************************************************/ const std::vector< int > PtNoise::mP = { 673, 514, 228, 3, 157, 394, 315, 202, 123, 20, 606, 878, 605, 77, 926, 117, 581, 850, 1019, 282, 665, 939, 604, 814, 7, 1006, 922, 27, 28, 835, 30, 822, 285, 255, 851, 400, 330, 927, 38, 39, 119, 240, 176, 391, 295, 142, 191, 67, 379, 49, 50, 93, 398, 873, 286, 127, 693, 669, 793, 1020, 559, 278, 140, 410, 430, 411, 46, 47, 736, 13, 481, 160, 246, 772, 318, 82, 367, 660, 78, 291, 863, 445, 727, 483, 745, 968, 622, 894, 838, 661, 90, 91, 335, 700, 94, 994, 549, 97, 945, 161, 486, 340, 8, 418, 104, 303, 344, 232, 588, 45, 503, 615, 284, 787, 71, 728, 544, 691, 762, 149, 634, 452, 996, 203, 505, 178, 58, 638, 220, 260, 130, 139, 934, 16, 958, 631, 194, 967, 511, 195, 441, 181, 1015, 970, 999, 907, 911, 458, 815, 252, 808, 151, 53, 672, 671, 929, 658, 697, 251, 215, 819, 846, 267, 226, 689, 239, 518, 836, 210, 68, 771, 171, 943, 336, 235, 685, 893, 270, 349, 839, 180, 914, 182, 125, 901, 504, 597, 978, 862, 189, 783, 976, 1009, 844, 66, 859, 806, 109, 530, 871, 896, 539, 805, 348, 204, 205, 417, 720, 128, 237, 992, 25, 991, 773, 214, 159, 977, 80, 841, 219, 73, 292, 465, 813, 320, 225, 163, 227, 993, 229, 230, 231, 913, 407, 904, 371, 256, 872, 238, 65, 833, 306, 242, 243, 385, 831, 995, 148, 341, 22, 713, 334, 192, 253, 965, 100, 201, 257, 294, 321, 809, 590, 343, 959, 188, 853, 902, 95, 905, 633, 366, 383, 5, 652, 937, 135, 494, 710, 183, 395, 280, 325, 480, 308, 670, 92, 974, 287, 612, 431, 855, 589, 607, 677, 722, 949, 342, 353, 523, 299, 300, 301, 356, 738, 450, 305, 402, 268, 359, 854, 576, 196, 116, 313, 908, 548, 316, 538, 377, 168, 572, 690, 459, 307, 887, 85, 326, 533, 856, 51, 798, 437, 746, 111, 107, 600, 816, 389, 1022, 382, 743, 567, 358, 528, 923, 439, 323, 223, 103, 373, 350, 351, 32, 776, 397, 29, 245, 715, 216, 442, 766, 361, 521, 19, 912, 224, 427, 752, 368, 234, 254, 174, 546, 478, 363, 208, 34, 74, 378, 155, 447, 463, 425, 384, 108, 566, 721, 150, 388, 337, 825, 37, 989, 915, 261, 279, 675, 885, 666, 596, 903, 401, 571, 24, 852, 657, 75, 169, 36, 409, 990, 560, 786, 1018, 324, 415, 502, 346, 63, 707, 900, 547, 740, 579, 455, 218, 18, 580, 428, 244, 531, 289, 432, 433, 906, 701, 436, 331, 414, 88, 297, 200, 131, 443, 115, 594, 703, 217, 129, 678, 552, 406, 121, 453, 870, 561, 884, 86, 310, 562, 557, 823, 462, 381, 1, 986, 102, 467, 920, 969, 477, 298, 52, 626, 474, 355, 471, 770, 587, 42, 281, 118, 479, 613, 592, 83, 784, 365, 488, 360, 765, 491, 492, 522, 731, 647, 137, 529, 498, 4, 500, 617, 11, 540, 273, 464, 328, 507, 508, 490, 197, 369, 364, 15, 961, 290, 988, 264, 629, 1007, 987, 495, 81, 272, 524, 824, 166, 527, 193, 653, 1008, 880, 532, 889, 69, 535, 536, 812, 723, 712, 955, 422, 542, 718, 637, 954, 510, 421, 794, 236, 120, 868, 412, 608, 277, 79, 556, 555, 309, 403, 213, 434, 212, 898, 973, 493, 732, 35, 170, 569, 570, 725, 57, 709, 769, 938, 472, 619, 578, 761, 515, 802, 749, 352, 910, 698, 302, 956, 435, 399, 623, 444, 10, 136, 473, 779, 262, 405, 598, 526, 475, 897, 602, 739, 879, 370, 283, 271, 944, 89, 610, 792, 599, 429, 639, 132, 616, 803, 618, 936, 59, 259, 33, 925, 696, 250, 734, 627, 724, 826, 630, 628, 152, 985, 877, 635, 222, 101, 892, 960, 591, 931, 187, 456, 834, 916, 646, 54, 789, 179, 680, 651, 1004, 857, 460, 64, 206, 748, 156, 499, 184, 0, 952, 778, 664, 869, 269, 759, 979, 843, 112, 23, 941, 942, 496, 258, 624, 714, 656, 611, 338, 962, 1001, 683, 684, 935, 643, 681, 275, 413, 509, 207, 692, 755, 1011, 860, 818, 122, 70, 828, 662, 21, 84, 470, 963, 705, 550, 380, 387, 154, 764, 96, 339, 575, 733, 449, 317, 717, 788, 497, 134, 512, 781, 767, 393, 867, 241, 1021, 553, 519, 797, 593, 642, 757, 729, 735, 534, 737, 583, 791, 72, 668, 742, 14, 1013, 890, 585, 141, 565, 830, 795, 751, 296, 753, 754, 485, 849, 26, 758, 980, 332, 423, 747, 625, 327, 345, 645, 114, 87, 347, 609, 420, 774, 319, 322, 655, 162, 777, 883, 595, 780, 957, 782, 304, 31, 785, 173, 167, 649, 760, 153, 1012, 614, 948, 886, 601, 796, 730, 997, 799, 659, 333, 489, 874, 804, 667, 875, 807, 790, 933, 810, 848, 506, 60, 487, 586, 372, 817, 636, 221, 98, 821, 554, 708, 876, 964, 124, 165, 469, 829, 704, 248, 641, 741, 543, 288, 858, 953, 147, 454, 840, 12, 76, 190, 461, 845, 837, 847, 44, 891, 687, 158, 516, 265, 199, 482, 1000, 971, 266, 654, 438, 861, 177, 525, 864, 865, 468, 702, 551, 56, 568, 408, 390, 811, 476, 679, 881, 558, 632, 249, 314, 41, 882, 621, 577, 396, 711, 55, 888, 138, 145, 133, 311, 448, 603, 895, 983, 110, 563, 744, 172, 650, 564, 209, 775, 113, 573, 376, 211, 185, 688, 146, 582, 517, 584, 424, 620, 917, 918, 919, 866, 921, 676, 827, 924, 43, 975, 966, 928, 466, 930, 233, 932, 644, 446, 99, 106, 501, 768, 440, 998, 198, 820, 175, 541, 695, 946, 329, 186, 719, 950, 951, 357, 17, 545, 263, 40, 726, 386, 947, 756, 404, 537, 374, 62, 640, 247, 457, 686, 520, 143, 842, 126, 763, 2, 451, 513, 663, 682, 706, 972, 981, 982, 9, 984, 426, 694, 144, 674, 419, 362, 105, 416, 832, 48, 909, 274, 1002, 574, 293, 164, 484, 699, 1003, 312, 354, 276, 801, 648, 940, 1010, 800, 1005, 899, 1014, 61, 1016, 1017, 392, 716, 6, 750, 375, 1023 }; const std::vector< float > PtNoise::mRndTab = { -0.20707f, 0.680971f, -0.293328f, -0.106833f, -0.362614f, 0.772857f, -0.968834f, 0.16818f, -0.681263f, -0.232568f, 0.382009f, -0.882282f, 0.799709f, -0.672908f, -0.681857f, 0.0661294f, 0.208288f, 0.165398f, -0.460058f, -0.219044f, -0.413199f, 0.484755f, -0.402949f, -0.848924f, -0.190035f, 0.714756f, 0.883937f, 0.325661f, 0.692952f, -0.99449f, -0.0752415f, 0.0651921f, 0.575753f, -0.468776f, 0.965505f, -0.38643f, 0.20171f, 0.217431f, -0.575122f, 0.77179f, -0.390686f, -0.69628f, -0.324676f, -0.225046f, 0.28722f, 0.507107f, 0.207232f, 0.0632565f, -0.0812794f, 0.304977f, -0.345638f, 0.892741f, -0.26392f, 0.887781f, -0.985143f, 0.0331999f, -0.454458f, -0.951402f, 0.183909f, -0.590073f, 0.755387f, -0.881263f, -0.478315f, -0.394342f, 0.78299f, -0.00360388f, 0.420051f, -0.427172f, 0.729847f, 0.351081f, -0.08302f, 0.919271f, 0.549351f, -0.246897f, -0.542722f, -0.290932f, -0.399364f, 0.339532f, 0.437933f, 0.131909f, 0.648931f, -0.218776f, 0.637533f, 0.688017f, -0.639064f, 0.886792f, -0.150226f, 0.0413315f, -0.868712f, 0.827016f, 0.765169f, 0.522728f, -0.202155f, 0.376514f, 0.523097f, -0.189982f, -0.749498f, -0.0307322f, -0.555075f, 0.746242f, 0.0576438f, -0.997172f, 0.721028f, -0.962605f, 0.629784f, -0.514232f, -0.370856f, 0.931465f, 0.87112f, 0.618863f, -0.0157817f, -0.559729f, 0.152707f, -0.421942f, -0.357866f, -0.477353f, -0.652024f, -0.996365f, -0.910432f, -0.517651f, -0.169098f, 0.403249f, -0.556309f, 0.00782073f, -0.86594f, -0.213873f, -0.0410469f, -0.563716f, -0.560977f, 0.832406f, -0.299556f, -0.614612f, -0.57753f, 0.267363f, -0.892869f, 0.566823f, -0.938652f, -0.111807f, -0.647174f, 0.86436f, 0.819297f, -0.0543103f, 0.743391f, 0.391135f, 0.860379f, -0.0898189f, -0.202866f, 0.786608f, 0.387094f, 0.677469f, 0.479398f, 0.302539f, 0.356308f, 0.154425f, -0.453763f, 0.870776f, 0.323878f, -0.905175f, -0.253923f, 0.23639f, -0.702744f, -0.245389f, 0.289183f, -0.948624f, 0.682761f, -0.845962f, 0.485268f, -0.488028f, 0.803688f, -0.244705f, -0.36094f, -0.57713f, 0.297065f, -0.49737f, -0.542711f, -0.498156f, 0.886442f, -0.72657f, -0.459878f, 0.0974144f, -0.351957f, 0.73016f, -0.406593f, 0.360119f, 0.666294f, 0.752615f, 0.299329f, -0.853769f, 0.797094f, -0.492837f, 0.222637f, 0.68378f, 0.664039f, -0.254826f, 0.514096f, -0.78157f, 0.701624f, 0.118659f, 0.715161f, -0.313806f, 0.383539f, -0.309605f, 0.787169f, 0.917416f, -0.75653f, 0.963089f, -0.88995f, 0.229553f, -0.923747f, -0.247055f, 0.0512097f, -0.436152f, 0.121076f, 0.214486f, 0.632879f, -0.10693f, -0.945777f, -0.056292f, -0.430203f, -0.414553f, -0.60864f, -0.964841f, 0.659198f, 0.146331f, -0.790439f, 0.465953f, -0.761805f, -0.552223f, 0.894506f, 0.478103f, 0.642714f, 0.652263f, -0.49804f, -0.487009f, -0.323614f, -0.223557f, 0.054637f, -0.467182f, -0.197559f, 0.741789f, -0.908216f, -0.410852f, -0.211507f, 0.120005f, -0.378358f, 0.645154f, -0.049037f, -0.817713f, -0.475198f, 0.834088f, 0.956872f, -0.335813f, 0.804148f, -0.51873f, -0.253671f, 0.504572f, -0.0843452f, 0.801256f, -0.154211f, 0.131847f, 0.940924f, -0.292258f, -0.136987f, -0.641817f, -0.569362f, -0.325646f, -0.0912645f, -0.910549f, 0.367765f, -0.875702f, 0.102751f, -0.367658f, -0.463564f, 0.00153196f, -0.874926f, 0.929653f, 0.459152f, 0.612631f, -0.696051f, 0.410036f, 0.459915f, 0.685132f, 0.235857f, 0.910896f, -0.0412238f, 0.054171f, -0.941227f, 0.215224f, -0.904861f, 0.185539f, -0.194706f, 0.808789f, -0.339738f, -0.378325f, 0.70989f, 0.468299f, -0.802747f, -0.319083f, -0.196521f, 0.970334f, 0.25919f, 0.663925f, -0.125761f, 0.582453f, -0.881076f, -0.72973f, 0.0876478f, 0.860903f, 0.769798f, -0.220211f, -0.170885f, 0.713725f, -0.426483f, -0.784487f, 0.153352f, 0.555204f, -0.715498f, 0.617354f, 0.496188f, -0.17995f, -0.0497684f, -0.311081f, -0.166402f, -0.952704f, 0.051622f, 0.435783f, -0.527955f, 0.38973f, 0.559901f, 0.525501f, -0.756875f, -0.258964f, 0.856503f, 0.532013f, -0.420841f, 0.967321f, -0.143786f, -0.924374f, 0.196653f, -0.968809f, 0.513448f, -0.738642f, -0.250866f, -0.565008f, 0.155594f, -0.588673f, 0.574042f, 0.496738f, -0.0893272f, -0.429463f, 0.70044f, -0.0999849f, 0.670024f, -0.139508f, -0.338008f, 0.901744f, -0.502254f, -0.286412f, -0.164259f, -0.00589371f, 0.770586f, 0.126331f, 0.371001f, 0.935519f, -0.635262f, 0.135611f, -0.940671f, -0.592076f, -0.68447f, 0.0951887f, -0.592019f, -0.577427f, -0.865412f, -0.613805f, 0.803043f, 0.564099f, -0.39482f, -0.155984f, 0.979051f, 0.594241f, -0.225057f, -0.636119f, -0.550537f, 0.474766f, 0.0670141f, 0.329472f, -0.596338f, -0.0623523f, 0.132995f, -0.805072f, -0.445953f, -0.965377f, 0.127768f, 0.773879f, -0.85962f, -0.875958f, -0.493386f, -0.385871f, 0.79328f, -0.731853f, 0.89542f, -0.141091f, -0.843747f, 0.567334f, -0.112659f, -0.157636f, 0.403773f, -0.620359f, -0.74756f, -0.503881f, 0.315856f, -0.724989f, -0.354449f, 0.645029f, -0.972318f, 0.847415f, -0.247293f, 0.164137f, -0.477254f, -0.172582f, 0.375393f, 0.507442f, -0.657344f, -0.741592f, -0.682019f, -0.414483f, 0.715187f, -0.442246f, 0.376847f, 0.677779f, 0.629953f, -0.902771f, -0.854116f, -0.138042f, 0.499652f, -0.696091f, -0.175465f, -0.794968f, 0.522245f, 0.283572f, 0.469819f, 0.0948274f, -0.800236f, 0.464648f, 0.0576595f, 0.038949f, -0.427001f, 0.894641f, -0.147727f, -0.0114098f, 0.40495f, -0.483555f, 0.622736f, 0.760873f, -0.997745f, -0.785802f, -0.453497f, 0.967972f, -0.277754f, 0.633599f, 0.710523f, -0.421174f, 0.998972f, -0.982482f, -0.872429f, 0.935388f, 0.366325f, -0.396888f, 0.450846f, 0.84717f, 0.298028f, 0.831535f, 0.0722433f, 0.953355f, -0.533049f, -0.162882f, 0.163758f, 0.560595f, -0.59966f, 0.802104f, -0.741726f, 0.857332f, 0.529727f, -0.0405177f, 0.112755f, -0.975824f, -0.232527f, -0.24467f, 0.457103f, 0.0876135f, 0.355111f, 0.179531f, -0.434472f, -0.784347f, -0.402533f, 0.057541f, 0.810026f, -0.125382f, 0.902344f, -0.535312f, 0.0399954f, 0.233073f, -0.623447f, 0.958511f, 0.00639474f, -0.679882f, 0.0790659f, -0.614876f, -0.501872f, -0.339625f, -0.698238f, 0.245166f, -0.576554f, 0.887646f, 0.244024f, -0.572648f, -0.0526508f, 0.685447f, -0.117632f, -0.761956f, 0.840836f, 0.348531f, -0.670558f, 0.560047f, 0.419046f, -0.630359f, 0.553467f, -0.569617f, -0.490988f, 0.325722f, 0.921231f, 0.884165f, 0.616011f, 0.594694f, 0.972902f, 0.399779f, 0.329042f, -0.764266f, 0.379393f, -0.68921f, -0.344626f, -0.097562f, -0.176869f, 0.0149344f, 0.692548f, 0.649795f, 0.137582f, 0.383956f, -0.719118f, 0.694652f, 0.402503f, -0.5849f, -0.866093f, -0.121557f, 0.689953f, -0.397973f, -0.321879f, 0.0748543f, -0.934146f, 0.757382f, -0.637111f, 0.929531f, 0.455039f, -0.109972f, 0.598553f, -0.00921971f, -0.337852f, -0.692814f, 0.474436f, -0.102178f, -0.299422f, 0.236665f, 0.883008f, -0.724233f, 0.517349f, -0.910394f, 0.173275f, 0.315035f, -0.980193f, 0.933607f, -0.327466f, 0.689187f, 0.223563f, -0.975296f, 0.7046f, 0.0224042f, -0.531078f, 0.34089f, 0.604275f, -0.879452f, 0.52088f, 0.237137f, 0.848053f, -0.276448f, -0.592991f, -0.348802f, 0.112302f, 0.748835f, 0.896259f, -0.939266f, -0.189234f, 0.533631f, 0.323923f, 0.737031f, 0.588107f, 0.138091f, 0.17416f, 0.151135f, 0.146229f, -0.438567f, 0.4982f, -0.161338f, 0.602722f, -0.997772f, -0.663456f, 0.0747519f, 0.929268f, 0.844336f, -0.803741f, 0.58706f, -0.347807f, 0.68648f, -0.914757f, -0.240175f, -0.666555f, -0.198301f, -0.694225f, -0.345168f, -0.0395932f, 0.289883f, -0.752425f, 0.275475f, 0.485683f, 0.780465f, 0.790232f, -0.810475f, 0.758027f, -0.207396f, -0.973497f, 0.547203f, 0.0139524f, -0.762494f, -0.841653f, 0.107478f, -0.84642f, 0.553916f, -0.690491f, -0.17762f, -0.942622f, 0.636364f, 0.261143f, -0.687253f, 0.222471f, 0.111039f, 0.775731f, -0.0331696f, -0.325886f, -0.768171f, -0.83886f, -0.0455701f, -0.738002f, 0.336049f, 0.378831f, -0.99628f, -0.439122f, -0.426069f, 0.56223f, 0.947077f, -0.704819f, -0.302501f, -0.0665605f, -0.301488f, 0.789032f, -0.216332f, -0.654522f, 0.152676f, 0.853504f, -0.374663f, -0.00410563f, -0.551168f, -0.134369f, 0.435965f, 0.125214f, 0.859039f, 0.828424f, -0.207817f, 0.00542223f, 0.255695f, -0.156154f, 0.231101f, 0.421414f, -0.511748f, 0.753763f, -0.499045f, -0.26024f, 0.132566f, -0.564272f, -0.456005f, -0.961464f, -0.16984f, 0.265878f, 0.308314f, -0.460366f, -0.0486212f, -0.878744f, -0.588512f, -0.452418f, -0.480284f, 0.685756f, 0.515324f, -0.530612f, 0.429637f, 0.101136f, 0.550935f, 0.387332f, -0.0366921f, 0.676956f, -0.778804f, 0.606455f, 0.730367f, 0.606859f, 0.59914f, 0.0323113f, -0.531947f, 0.755581f, 0.262923f, 0.990242f, 0.976722f, -0.439991f, -0.0811486f, -0.0807913f, 0.939347f, 0.0632279f, 0.553093f, 0.411404f, -0.124347f, -0.136165f, -0.959233f, -0.619912f, 0.185786f, -0.738866f, -0.919931f, 0.185369f, -0.3999f, 0.713647f, 0.0921651f, -0.3001f, 0.606923f, -0.336502f, 0.149248f, 0.329354f, -0.903224f, 0.228558f, 0.409017f, 0.597411f, 0.838132f, 0.800225f, -0.679005f, -0.849974f, 0.066663f, 0.435656f, 0.936607f, -0.0771584f, -0.211812f, 0.484105f, 0.940352f, -0.850672f, -0.992062f, 0.178693f, 0.994419f, 0.172109f, 0.429005f, -0.845299f, 0.155544f, 0.368904f, -0.0838963f, -0.123131f, 0.514225f, -0.463254f, -0.316715f, -0.218999f, -0.113225f, -0.181078f, -0.49629f, -0.774654f, 0.956039f, 0.640184f, 0.804682f, -0.0728759f, 0.333761f, -0.524985f, 0.132087f, 0.907606f, 0.764773f, 0.855232f, 0.756395f, -0.279823f, -0.70013f, -0.522577f, -0.95987f, 0.180812f, 0.45117f, 0.154243f, 0.267937f, 0.406582f, -0.137258f, -0.370685f, -0.0897717f, -0.201184f, 0.16377f, -0.187431f, 0.486166f, 0.942996f, -0.26433f, -0.933307f, 0.329012f, 0.153509f, 0.964356f, -0.0324244f, -0.564532f, 0.640186f, 0.0410044f, -0.939893f, 0.280686f, -0.256316f, -0.0724265f, 0.0296069f, -0.136661f, 0.262995f, 0.156279f, -0.69113f, 0.453271f, -0.878359f, 0.656072f, -0.752054f, -0.528582f, 0.186816f, -0.204273f, -0.198698f, 0.843176f, 0.321241f, 0.835749f, -0.646054f, -0.981633f, 0.220718f, -0.445718f, 0.339949f, -0.0889146f, -0.562843f, -0.948627f, -0.864842f, -0.670193f, -0.470315f, 0.768155f, 0.168599f, 0.372232f, 0.503568f, 0.241067f, 0.0384121f, 0.861864f, 0.723146f, 0.735475f, 0.78832f, -0.403295f, 0.111575f, 0.888819f, 0.456458f, -0.861308f, -0.375725f, 0.0924894f, 0.0126309f, 0.550513f, 0.308125f, -0.662566f, 0.221904f, 0.120679f, -0.505715f, -0.544765f, 0.5873f, -0.774288f, 0.235227f, -0.550015f, 0.0138385f, -0.64114f, -0.441786f, 0.313562f, 0.288163f, 0.587974f, 0.696802f, -0.743927f, 0.876665f, -0.347592f, 0.563469f, 0.603839f, 0.31075f, -0.787441f, 0.381486f, 0.189887f, 0.857299f, -0.150132f, 0.79965f, 0.388627f, 0.978384f, 0.984722f, -0.176776f, -0.939742f, 0.886053f, 0.42117f, 0.517951f, -0.363949f, 0.32082f, 0.508184f, -0.652452f, -0.0113876f, 0.458137f, -0.523753f, -0.989305f, 0.218567f, -0.0866277f, -0.804653f, 0.229887f, -0.791075f, -0.583133f, 0.0174403f, 0.746333f, -0.0597281f, -0.483113f, -0.594472f, 0.0833201f, -0.155518f, -0.803679f, -0.613321f, 0.902488f, -0.346171f, -0.478224f, 0.45257f, 0.0966891f, 0.559465f, -0.749715f, -0.895227f, 0.399409f, -0.657407f, -0.0252426f, 0.82075f, -0.840023f, -0.670942f, 0.0760187f, -0.401039f, 0.108451f, -0.579594f, -0.945201f, -0.492007f, 0.142416f, -0.519982f, -0.764514f, -0.32379f, -0.705026f, -0.558962f, 0.265189f, 0.0579748f, 0.629764f, -0.375703f, -0.916671f, -0.976436f, 0.552299f, -0.0888248f, 0.321525f, -0.452217f, 0.280738f, 0.141571f, 0.530024f, -0.496806f, 0.493166f, -0.034681f, 0.740796f, -0.434634f, -0.371416f, 0.462175f, 0.100296f, -0.441395f, 0.28735f, 0.287906f, -0.525333f, -0.958905f, 0.63229f, -0.439815f, -0.209011f, -0.340195f, 0.768903f, 0.857426f, 0.580399f, -0.309656f, -0.427039f, 0.787087f, 0.789257f, -0.61095f, -0.716271f, 0.839248f, -0.114208f, -0.220958f, -0.00560474f, -0.540353f, 0.981056f, 0.505123f, -0.292023f, -0.731658f, 0.879887f, 0.94177f, -0.69709f, -0.538658f, 0.361588f, -0.877064f, -0.860003f, 0.0400107f, -0.350923f, -0.13797f, -0.630015f, -0.475121f, -0.0465513f, 0.00653064f, 0.653369f, -0.833781f, 0.578648f, -0.233113f }; const std::vector< float > PtNoise::mG = { -0.995337f,-0.0963314f,0.00495357f, -0.127269f,-0.895402f,-0.426682f, -0.584669f,-0.639987f,-0.498577f, -0.256759f,-0.0351604f,-0.965836f, 0.230517f,0.0496408f,-0.971801f, -0.157628f,0.973101f,-0.168009f, -0.39926f,0.901399f,-0.167542f, -0.626804f,-0.141564f,-0.766209f, -0.807439f,0.550296f,-0.212643f, 0.506836f,0.774449f,-0.37861f, -0.502156f,0.551161f,-0.666379f, 0.766853f,0.641784f,0.00707779f, -0.286142f,-0.941352f,0.178827f, -0.0441219f,-0.0135373f,0.998934f, -0.855989f,-0.408854f,-0.316419f, -0.881202f,-0.446996f,0.153875f, -0.140249f,-0.254445f,0.956863f, -0.24534f,-0.17324f,-0.953832f, -0.617697f,-0.569507f,0.542321f, 0.753917f,0.495649f,-0.431208f, -0.573983f,-0.1481f,0.805363f, -0.81193f,0.5261f,-0.252961f, -0.452386f,-0.705251f,-0.545865f, -0.242218f,-0.870244f,-0.428958f, -0.950431f,0.31004f,-0.0235713f, 0.802699f,0.565195f,-0.19034f, -0.746878f,0.664283f,0.030028f, -0.896907f,0.153356f,-0.414778f, -0.748329f,-0.202457f,0.631676f, -0.528151f,0.840434f,0.121355f, -0.0162022f,-0.130013f,-0.99138f, -0.584409f,0.137181f,0.79978f, -0.789821f,-0.492396f,-0.365689f, 0.0624474f,0.150884f,0.986577f, -0.902876f,0.311719f,-0.29605f, -0.270693f,0.88754f,-0.372825f, 0.964165f,0.0552917f,0.259479f, 0.98341f,0.171571f,0.0588914f, 0.789046f,0.394704f,0.47076f, 0.0946113f,0.249194f,0.963821f, 0.897137f,-0.366363f,-0.246827f, -0.391713f,-0.531864f,-0.750787f, -0.198871f,0.96269f,-0.183518f, 0.00930338f,-0.985714f,0.16817f, 0.550144f,-0.308657f,0.775933f, 0.541166f,-0.664553f,0.515275f, -0.173206f,-0.440895f,0.880688f, -0.107763f,0.682367f,-0.723023f, 0.094759f,0.165702f,-0.981613f, 0.105035f,-0.730918f,-0.674335f, -0.124068f,0.0584148f,-0.990553f, -0.900757f,0.433876f,-0.0197054f, -0.279353f,0.0175174f,-0.960029f, -0.862581f,0.450873f,-0.229493f, 0.0118461f,0.0393322f,0.999156f, 0.262375f,0.262377f,0.928611f, -0.158975f,0.415805f,-0.895452f, 0.976371f,-0.0116447f,-0.215789f, -0.27176f,-0.916866f,0.292409f, -0.54853f,-0.827749f,-0.118094f, 0.686411f,-0.448915f,-0.572115f, -0.632621f,-0.77415f,-0.0219575f, 0.887597f,0.135558f,0.440223f, 0.728919f,0.510989f,0.455596f, 0.380389f,-0.168086f,0.909423f, 0.645828f,-0.430376f,0.630621f, 0.246619f,0.14398f,-0.958357f, -0.685881f,0.525769f,-0.503125f, -0.517516f,-0.0410977f,-0.854686f, -0.463013f,-0.843602f,0.271945f, -0.0415956f,-0.991296f,-0.12491f, 0.141675f,0.970587f,0.194653f, -0.271737f,-0.923429f,0.270993f, 0.531673f,-0.0892442f,-0.842234f, -0.987587f,0.141071f,-0.0690721f, -0.184506f,-0.905782f,-0.381467f, 0.843001f,0.453146f,0.289841f, 0.598284f,0.764946f,0.238565f, 0.977912f,-0.137928f,-0.157046f, 0.621748f,-0.74933f,0.22789f, -0.780795f,-0.588364f,0.210208f, -0.220848f,-0.769464f,-0.599292f, 0.855617f,-0.251997f,0.452125f, 0.917424f,-0.342008f,0.203382f, 0.441082f,0.579448f,0.685337f, -0.509043f,0.0885631f,-0.856173f, 0.560355f,-0.656842f,-0.50454f, 0.548192f,0.571686f,-0.610459f, -0.716893f,-0.417658f,0.558235f, 0.464637f,-0.885467f,0.00780453f, -0.703826f,-0.6888f,0.173734f, -0.78906f,0.401402f,0.465038f, 0.0156625f,0.641766f,0.766741f, 0.294053f,0.866156f,-0.404111f, -0.102477f,-0.950015f,-0.294906f, -0.337476f,0.400548f,-0.851863f, -0.183512f,-0.166119f,-0.96888f, -0.761709f,0.630762f,-0.148116f, 0.574923f,0.602012f,0.554117f, 0.203744f,-0.853779f,-0.479113f, -0.00798792f,0.999737f,0.0215005f, 0.677404f,-0.391218f,0.622955f, -0.815094f,0.518173f,0.25907f, 0.132827f,-0.894498f,0.426884f, -0.593387f,-0.129533f,0.794426f, -0.598621f,-0.269058f,-0.754494f, 0.50647f,0.0429614f,-0.861187f, 0.513761f,-0.0873734f,0.853473f, 0.866916f,-0.466734f,-0.174973f, -0.457191f,0.831483f,-0.315615f, -0.299509f,0.734294f,0.609186f, -0.127551f,-0.199195f,0.971623f, 0.0474361f,0.740392f,-0.6705f, 0.158845f,-0.987133f,0.0183756f, -0.286056f,-0.45995f,0.840606f, -0.56238f,0.562325f,-0.606233f, 0.675337f,0.489026f,-0.552063f, -0.962879f,0.0183395f,0.269311f, 0.594715f,-0.226561f,0.771352f, 0.763063f,0.128532f,0.633415f, -0.206158f,0.339559f,0.917714f, 0.859512f,0.510172f,-0.0310404f, -0.0660017f,-0.0518204f,0.996473f, -0.150708f,-0.970199f,0.189737f, 0.264597f,-0.781519f,0.564993f, -0.497814f,0.572053f,0.651871f, 0.501956f,0.683997f,-0.529328f, -0.282503f,-0.950973f,0.125865f, 0.1352f,-0.988438f,-0.06864f, -0.282702f,0.638228f,-0.716062f, -0.656422f,0.0287193f,-0.753847f, 0.208379f,-0.908798f,0.361475f, -0.449788f,0.803432f,0.390113f, 0.497612f,-0.195281f,0.845132f, 0.478706f,-0.591182f,0.64911f, 0.332439f,0.65519f,-0.678388f, -0.224547f,0.931102f,0.287451f, 0.866684f,0.173673f,0.46765f, -0.642039f,0.527463f,0.55639f, 0.821565f,0.569369f,0.0291539f, -0.0965395f,0.227327f,-0.969021f, 0.485838f,0.08013f,0.870368f, 0.41181f,0.863865f,-0.290087f, -0.877688f,0.468305f,0.101758f, 0.900076f,-0.262106f,-0.348086f, 0.350322f,-0.595606f,-0.722861f, -0.997071f,0.0479511f,-0.0595866f, -0.4779f,0.47159f,-0.74109f, 0.784974f,-0.0653942f,0.616068f, -0.942425f,0.127952f,-0.308971f, 0.488343f,-0.775291f,-0.400557f, 0.578381f,-0.63869f,0.507494f, 0.988325f,-0.0779259f,-0.130922f, 0.641157f,-0.374007f,-0.670102f, -0.228031f,0.9065f,0.35533f, -0.25019f,-0.838703f,-0.483718f, 0.0810177f,-0.0996475f,0.991719f, 0.318871f,-0.816779f,0.480825f, -0.527652f,0.849221f,0.0201835f, -0.413265f,-0.86432f,0.286641f, 0.262444f,0.919294f,-0.293294f, 0.0588558f,0.511168f,0.857463f, -0.488005f,0.382953f,0.784346f, 0.476994f,-0.244857f,-0.84411f, 0.299166f,0.928119f,-0.221575f, -0.173116f,0.631585f,0.755732f, 0.936239f,0.296925f,0.187862f, 0.28606f,-0.621213f,-0.729564f, -0.763401f,0.584881f,0.274105f, -0.349918f,-0.209879f,0.912966f, -0.895935f,0.433536f,0.0966801f, -0.6814f,-0.670747f,0.292904f, 0.136759f,-0.79238f,-0.594501f, 0.822134f,0.562461f,0.0879401f, 0.424749f,0.683623f,-0.593504f, -0.0747487f,0.715274f,0.694835f, -0.459191f,-0.281188f,-0.84266f, 0.320708f,-0.316255f,0.892821f, -0.000195973f,0.968471f,0.249128f, 0.977116f,0.212104f,-0.0160051f, -0.233741f,0.0498687f,0.971019f, -0.848421f,-0.457529f,0.266176f, 0.908748f,0.240219f,-0.341281f, 0.887017f,0.384523f,0.255621f, 0.56382f,0.778539f,0.275653f, 0.420234f,0.869223f,0.26049f, 0.82864f,0.472263f,-0.300539f, -0.180138f,0.972185f,-0.14969f, -0.46077f,-0.161684f,0.872668f, -0.461698f,-0.774814f,0.431854f, 0.378634f,0.84215f,-0.383953f, -0.150442f,0.469605f,0.869965f, 0.989448f,0.0447963f,-0.137789f, 0.525245f,-0.588033f,-0.61509f, -0.130293f,-0.363557f,0.922415f, 0.189538f,0.277437f,-0.941862f, 0.57935f,0.799426f,-0.158971f, -0.401727f,-0.256848f,0.879002f, -0.0267194f,0.00601085f,-0.999625f, 0.323036f,0.025283f,0.946049f, 0.575425f,0.759032f,0.30456f, 0.291424f,-0.264203f,-0.919385f, 0.749912f,0.600642f,-0.277238f, -0.103694f,-0.458468f,-0.88264f, 0.388725f,-0.884519f,0.257912f, 0.820942f,0.205512f,-0.532747f, 0.881102f,0.373738f,0.289793f, 0.646729f,0.643122f,0.410043f, -0.69647f,-0.103343f,0.710106f, -0.758958f,0.593995f,0.266743f, -0.806636f,-0.438702f,-0.396079f, -0.672382f,0.689798f,0.268479f, 0.238804f,-0.916859f,0.319911f, -0.336248f,0.863687f,0.375477f, 0.790803f,0.156416f,-0.591746f, -0.944496f,-0.262094f,0.198074f, 0.30435f,0.534205f,0.788667f, 0.890343f,-0.286362f,-0.353959f, -0.385709f,-0.820423f,-0.42206f, 0.274585f,0.0339316f,-0.960964f, -0.396699f,-0.881564f,-0.255881f, 0.25842f,0.817563f,-0.514596f, 0.547517f,0.294833f,0.783134f, 0.553166f,-0.677312f,-0.485031f, -0.858922f,-0.472283f,-0.197996f, -0.0951316f,0.975694f,-0.19741f, -0.299695f,-0.17562f,-0.937732f, -0.082973f,-0.280427f,0.956282f, -0.349532f,-0.712517f,-0.608397f, -0.136338f,0.826922f,-0.545538f, 0.654914f,-0.521881f,-0.546561f, -0.469828f,-0.035166f,-0.882057f, 0.0968897f,-0.0902695f,-0.991193f, -0.479792f,-0.166208f,-0.861495f, 0.733615f,0.548993f,-0.40052f, -0.801972f,0.0949268f,-0.589771f, 0.771141f,0.00319058f,0.636657f, 0.952318f,0.206405f,-0.224695f, -0.705452f,0.105686f,-0.700834f, 0.852339f,0.117083f,-0.509715f, -0.467995f,0.821103f,0.326758f, 0.157773f,-0.619175f,-0.76924f, 0.70127f,0.120451f,-0.702646f, -0.59492f,0.801578f,0.0595336f, 0.213569f,-0.493667f,0.843019f, -0.80494f,0.56206f,-0.190162f, -0.171186f,0.93397f,-0.31368f, -0.299164f,0.370468f,0.879349f, 0.493235f,-0.611316f,0.618879f, 0.581282f,0.453523f,0.675595f, 0.593582f,-0.603139f,0.532808f, -0.909646f,-0.358179f,-0.210362f, 0.559869f,-0.662772f,0.497272f, -0.191802f,0.608544f,-0.769991f, 0.346122f,-0.661244f,0.665549f, 0.0296552f,-0.568236f,0.822331f, 0.106132f,0.228959f,0.967633f, -0.201356f,0.570967f,-0.795897f, -0.568292f,0.258763f,-0.78108f, 0.424616f,0.457506f,0.781274f, 0.116078f,0.951826f,-0.28382f, -0.17797f,-0.693f,-0.698625f, -0.459185f,0.886223f,0.0613055f, 0.79617f,-0.406076f,0.448571f, 0.668499f,0.0781926f,-0.739591f, 0.556856f,-0.563253f,-0.610456f, 0.519684f,-0.166455f,0.837987f, -0.863063f,-0.466105f,0.1946f, -0.16052f,-0.821449f,-0.547224f, -0.417444f,-0.571017f,-0.70688f, -0.946456f,0.0218126f,0.322095f, -0.904627f,-0.423336f,0.0493581f, -0.483063f,0.570092f,0.664564f, -0.622769f,-0.571464f,-0.534405f, 0.548214f,-0.526528f,-0.649792f, -0.441506f,0.748539f,0.494734f, 0.207318f,-0.789023f,-0.578327f, 0.635082f,0.680691f,-0.365144f, 0.613279f,-0.175911f,0.770028f, -0.471549f,-0.391471f,-0.790184f, 0.72864f,-0.107068f,0.676477f, -0.760403f,0.647205f,0.0539718f, 0.760361f,-0.0481715f,-0.647712f, -0.507843f,-0.837564f,-0.201448f, -0.948893f,0.266992f,0.168279f, -0.598596f,0.568604f,0.564245f, 0.14618f,0.399532f,0.904989f, -0.456872f,-0.720548f,-0.521612f, 0.970891f,-0.0635678f,0.230931f, 0.0455778f,-0.906543f,0.419645f, 0.237166f,0.836401f,0.494152f, -0.260743f,-0.50237f,-0.824401f, 0.710043f,-0.699867f,0.077623f, -0.119726f,0.968371f,-0.218916f, -0.148946f,-0.126901f,-0.980669f, -0.275976f,-0.90432f,0.325643f, 0.999836f,0.0179179f,0.00249936f, -0.0939087f,0.476906f,0.873923f, -0.552733f,-0.123589f,-0.824143f, -0.0899534f,0.0242877f,-0.99565f, 0.447809f,-0.237172f,0.8621f, 0.843561f,0.468681f,-0.262189f, -0.464399f,0.842563f,-0.272803f, 0.498392f,-0.847289f,0.183595f, -0.0987671f,-0.895783f,-0.43338f, 0.173854f,-0.607052f,-0.775412f, -0.950333f,0.256178f,0.17675f, -0.808452f,0.429147f,-0.402787f, 0.502984f,0.524146f,0.687225f, -0.875911f,0.430212f,-0.218399f, -0.146586f,-0.455835f,-0.87791f, 0.97173f,0.236009f,-0.00644619f, 0.151193f,0.913712f,-0.377189f, -0.899286f,0.3701f,0.233045f, 0.0279291f,-0.0191416f,-0.999427f, -0.435525f,0.142431f,-0.888837f, 0.622442f,0.57666f,0.529178f, -0.976959f,-0.10061f,-0.188223f, 0.0619783f,0.61406f,-0.786822f, 0.603997f,0.757401f,-0.248053f, 0.686297f,0.6924f,-0.222665f, -0.149721f,-0.879125f,0.452463f, 0.379971f,-0.0606177f,0.92301f, 0.454909f,0.855702f,-0.246642f, -0.684408f,-0.715119f,-0.142089f, 0.0525315f,-0.917494f,0.394265f, -0.984874f,0.0567441f,0.163716f, -0.376207f,0.151814f,0.914013f, -0.889986f,0.156507f,0.428287f, 0.0508916f,-0.896421f,0.440271f, 0.506201f,0.720106f,0.474561f, 0.501288f,0.621014f,-0.602538f, -0.2944f,0.809343f,-0.508226f, -0.405052f,0.759923f,-0.50838f, 0.650178f,-0.639888f,-0.409649f, 0.901284f,-0.423666f,-0.0905246f, -0.507972f,0.59907f,-0.618934f, 0.455528f,0.639878f,0.61891f, 0.230438f,0.551193f,0.801925f, 0.957581f,-0.266892f,-0.108663f, 0.918439f,0.0733391f,-0.388704f, 0.307095f,0.791491f,-0.528427f, 0.794804f,0.183304f,0.57852f, 0.989584f,-0.141784f,0.0248985f, 0.619738f,-0.4881f,-0.61456f, 0.583091f,0.807627f,0.0879972f, -0.0690386f,-0.895815f,-0.439031f, -0.242681f,0.934781f,-0.259406f, -0.917228f,0.390375f,-0.0793688f, 0.694195f,0.713333f,0.0961687f, 0.204567f,0.962897f,0.176014f, 0.828472f,0.302584f,0.471251f, 0.0296131f,0.253033f,0.967004f, 0.859933f,0.48926f,0.145392f, -0.833025f,-0.361335f,-0.418936f, 0.365287f,-0.907075f,0.209237f, 0.201145f,-0.508213f,-0.837413f, 0.753093f,-0.656592f,0.0416842f, -0.486135f,-0.807979f,0.332931f, 0.501133f,-0.272682f,-0.821286f, -0.62141f,0.781765f,0.0518952f, 0.243171f,0.969678f,0.024363f, 0.945886f,-0.278053f,0.16729f, -0.0738451f,-0.63738f,-0.767003f, -0.419787f,-0.822015f,0.3848f, 0.725214f,-0.238596f,-0.645862f, -0.201633f,-0.847229f,0.491475f, 0.688976f,-0.335423f,-0.642497f, -0.246371f,-0.944698f,0.21644f, 0.543639f,-0.723366f,0.425675f, -0.697446f,0.00653605f,0.716608f, -0.645581f,0.747664f,0.155641f, 0.949682f,0.304888f,-0.0717503f, 0.249783f,0.939622f,-0.23392f, 0.970653f,-0.221527f,0.0935835f, -0.338931f,0.940166f,0.0348405f, 0.428616f,-0.128976f,-0.894234f, -0.367967f,-0.726511f,0.58033f, -0.141686f,-0.955461f,-0.258879f, -0.0107806f,-0.809322f,-0.587266f, -0.877523f,-0.193574f,-0.438729f, -0.609099f,-0.720587f,-0.33129f, -0.0232971f,-0.252623f,-0.967284f, 0.852832f,-0.416386f,0.315118f, -0.344191f,-0.658291f,0.669467f, -0.858067f,0.155823f,-0.489325f, 0.802994f,0.505072f,0.316391f, 0.110778f,-0.945985f,-0.304697f, -0.0391144f,-0.607158f,0.793618f, 0.323963f,-0.841397f,0.432549f, -0.930926f,-0.124756f,0.343238f, 0.978689f,0.131815f,-0.157456f, 0.695575f,-0.143798f,-0.703916f, -0.372518f,-0.466024f,0.802529f, 0.427081f,0.116699f,-0.896651f, 0.692346f,0.686081f,-0.223497f, -0.304053f,-0.483534f,0.82082f, 0.110963f,-0.483387f,0.868346f, -0.375088f,-0.461682f,0.80384f, 0.410617f,-0.43438f,-0.801691f, -0.695892f,0.710809f,-0.102398f, 0.520786f,0.822262f,-0.229494f, 0.78752f,0.613848f,0.0547962f, 0.618469f,0.75722f,0.210032f, 0.363268f,-0.47695f,-0.800347f, -0.353503f,0.106097f,0.929397f, -0.666994f,0.524525f,-0.529143f, -0.370041f,-0.486017f,0.791743f, -0.0670981f,0.839184f,-0.539692f, 0.477306f,-0.793401f,0.377748f, -0.807242f,0.499964f,-0.313681f, -0.380399f,-0.557359f,-0.738003f, -0.855753f,-0.490483f,0.164658f, -0.449445f,0.214864f,-0.867083f, 0.987052f,0.0736918f,0.142474f, -0.213384f,-0.934849f,0.283768f, 0.402001f,0.202042f,-0.89307f, -0.350328f,0.863154f,-0.363643f, 0.881308f,0.389735f,0.267212f, 0.810928f,-0.539939f,-0.225527f, -0.803882f,0.402813f,-0.437626f, 0.983178f,0.0712831f,-0.168164f, -0.313511f,0.939613f,-0.137249f, -0.0557558f,0.501843f,0.86316f, -0.2634f,-0.963346f,-0.0508317f, -0.887735f,0.0502856f,-0.457601f, 0.779631f,0.0178821f,-0.625983f, 0.721641f,0.204139f,-0.661485f, 0.175877f,-0.00460269f,-0.984401f, -0.391104f,0.308647f,-0.867049f, 0.173799f,0.967745f,-0.182381f, -0.472131f,-0.870518f,0.138888f, 0.892767f,-0.174763f,-0.415241f, 0.712375f,-0.267541f,-0.648801f, 0.947792f,0.182506f,-0.261501f, 0.32635f,-0.909717f,0.25673f, 0.0693152f,-0.939587f,0.335218f, -0.134613f,0.966851f,0.216978f, -0.50317f,0.340791f,-0.794155f, -0.884992f,0.224023f,0.408169f, 0.947992f,0.124217f,-0.293054f, -0.081123f,0.778613f,0.622239f, -0.127847f,-0.898602f,0.419725f, -0.985676f,-0.163408f,-0.0417263f, 0.4092f,-0.701664f,-0.583287f, 0.727839f,0.244067f,0.640845f, 0.668931f,0.680546f,-0.29898f, 0.396423f,-0.76781f,0.503306f, -0.424051f,0.442895f,0.789952f, 0.886967f,-0.158771f,0.433683f, 0.702261f,0.357071f,-0.615897f, -0.115958f,0.0763258f,0.990317f, -0.43564f,0.649936f,-0.622737f, 0.745873f,-0.625853f,0.227994f, -0.142665f,0.984954f,-0.0975289f, 0.680993f,0.500709f,-0.534359f, -0.999546f,0.0287624f,-0.00896164f, 0.768709f,-0.622251f,0.147956f, -0.725784f,-0.146529f,-0.672136f, 0.301031f,-0.945686f,-0.122711f, 0.852468f,-0.411946f,-0.321867f, 0.855166f,0.249652f,0.454273f, 0.486952f,0.545704f,0.681971f, 0.932612f,-0.249845f,-0.260407f, -0.551691f,-0.620289f,-0.557565f, 0.451647f,0.0561142f,-0.89043f, 0.614931f,0.740299f,0.271693f, -0.525863f,-0.194253f,0.82809f, -0.760929f,-0.501261f,0.411976f, -0.582082f,-0.758714f,0.292462f, 0.154958f,0.190881f,-0.969305f, 0.0232719f,0.692175f,0.721354f, 0.0825491f,0.813035f,0.576333f, -0.5135f,-0.813996f,0.27153f, 0.114456f,-0.829863f,-0.546102f, -0.350331f,0.874281f,-0.336009f, 0.52785f,0.840282f,0.123692f, 0.354486f,-0.924629f,-0.13929f, -0.037307f,0.673782f,-0.737987f, 0.390652f,0.803224f,0.449692f, 0.801516f,0.438856f,0.406175f, -0.894495f,-0.389973f,-0.218633f, 0.977503f,0.210274f,0.0165066f, -0.75249f,-0.575843f,-0.31963f, 0.725406f,-0.681157f,0.0990522f, 0.412564f,-0.755349f,-0.509156f, -0.234163f,-0.813563f,-0.532243f, 0.28455f,-0.158259f,0.945508f, 0.0626414f,-0.85841f,-0.509125f, 0.496891f,0.742036f,0.44998f, 0.301236f,-0.291962f,-0.907753f, 0.507325f,0.634316f,0.583322f, -0.387737f,0.920932f,-0.0393046f, -0.0611886f,-0.963813f,0.259462f, 0.677932f,0.690938f,-0.251025f, 0.0513202f,0.910732f,-0.409797f, -0.298788f,-0.275131f,-0.913799f, 0.505485f,0.0569992f,0.860951f, 0.949484f,-0.171012f,-0.263125f, -0.906638f,-0.40222f,-0.127382f, -0.333593f,0.218367f,0.917078f, 0.27637f,-0.954606f,-0.111118f, -0.553207f,-0.494902f,-0.6701f, 0.685672f,-0.724434f,-0.071067f, -0.551433f,0.597155f,0.582518f, 0.410658f,-0.820487f,0.397695f, -0.317241f,-0.946822f,0.0537258f, 0.0606055f,-0.683621f,0.727316f, -0.950178f,0.0585999f,0.306151f, 0.174238f,0.466967f,-0.866939f, -0.134634f,-0.953982f,-0.267942f, -0.167232f,0.148768f,0.974629f, -0.294208f,0.895803f,0.333135f, -0.529987f,0.823075f,-0.204111f, 0.507014f,-0.857818f,-0.0841682f, 0.853806f,0.0117971f,-0.520457f, -0.268263f,-0.0512478f,0.961982f, -0.267144f,-0.807539f,-0.525847f, 0.0118146f,0.874617f,0.48467f, 0.528361f,0.443575f,-0.723931f, 0.590126f,0.399522f,-0.701523f, 0.577253f,0.42028f,0.700103f, 0.279723f,0.663015f,-0.694382f, 0.347782f,0.370998f,-0.861051f, 0.81373f,0.57449f,-0.0883443f, 0.836385f,0.127041f,-0.533217f, -0.695169f,-0.0451934f,-0.717425f, -0.540466f,0.384566f,0.748335f, -0.509764f,0.321001f,-0.798185f, 0.181449f,-0.983388f,-0.00491665f, 0.476414f,-0.825021f,0.303925f, -0.212088f,0.758226f,0.616532f, 0.357677f,-0.919317f,-0.164083f, -0.524163f,0.829261f,0.193852f, -0.22633f,-0.912899f,-0.339692f, -0.689936f,-0.692346f,0.211295f, -0.02498f,-0.998828f,0.0414504f, -0.00515593f,-0.485598f,0.874167f, -0.0280924f,0.985716f,-0.166059f, -0.82874f,0.559299f,-0.0193684f, 0.227957f,-0.361005f,-0.904274f, 0.190976f,-0.703633f,0.684419f, -0.0533315f,-0.883549f,0.465292f, -0.341919f,0.525239f,-0.779241f, -0.561624f,0.272391f,-0.781269f, -0.316527f,0.717616f,-0.620353f, -0.473525f,-0.850445f,0.229167f, 0.804116f,0.507518f,0.309552f, -0.12823f,0.751033f,-0.647693f, 0.981462f,0.146427f,0.123657f, 0.485328f,0.543513f,-0.684872f, 0.652835f,-0.201061f,0.73033f, -0.728664f,-0.474944f,-0.493434f, 0.733791f,0.105461f,0.67114f, 0.170424f,-0.800409f,0.574718f, 0.533732f,0.100186f,-0.839698f, -0.80571f,0.116569f,-0.580726f, 0.199806f,-0.86189f,0.466072f, -0.388735f,0.702065f,-0.596649f, 0.0824684f,-0.80804f,0.583327f, -0.952445f,-0.297644f,-0.0652421f, 0.342221f,-0.796293f,-0.498801f, 0.89842f,-0.354406f,0.259302f, 0.277112f,-0.818347f,-0.503504f, -0.450827f,-0.860188f,0.238394f, 0.326695f,0.00579992f,-0.945112f, -0.119248f,0.786188f,-0.606373f, 0.750576f,0.658761f,-0.0516659f, 0.317619f,-0.333866f,0.887497f, 0.38093f,0.303993f,0.873201f, 0.838676f,-0.50316f,-0.208453f, 0.0918522f,-0.359614f,-0.928569f, 0.0770786f,-0.996018f,0.0447966f, 0.0869882f,0.28308f,0.955143f, -0.235315f,-0.661291f,-0.712265f, 0.641471f,0.720919f,0.262278f, -0.870962f,-0.463816f,0.16217f, -0.706673f,0.695876f,-0.127949f, 0.902691f,0.3123f,-0.296004f, -0.496664f,0.0985662f,0.862328f, -0.794812f,0.483741f,0.366428f, -0.627241f,-0.488068f,-0.606925f, -0.577202f,-0.0462201f,0.815292f, -0.65584f,0.754899f,-0.000886882f, 0.0648057f,0.123395f,-0.990239f, -0.620726f,0.165652f,-0.766328f, -0.0162012f,-0.0317439f,0.999365f, 0.543344f,0.745653f,0.385718f, 0.555161f,-0.476917f,-0.68143f, 0.385476f,-0.38891f,0.836754f, 0.991037f,0.0265679f,-0.130918f, -0.226737f,-0.952803f,-0.201883f, -0.509995f,0.779489f,0.363733f, 0.127385f,-0.547623f,-0.826972f, -0.443689f,-0.602572f,0.66336f, -0.305934f,-0.668805f,0.677573f, 0.767099f,0.641494f,0.00668347f, -0.167729f,0.0827473f,-0.982354f, 0.240104f,-0.966031f,0.0955721f, 0.265511f,0.287718f,0.920175f, 0.17211f,-0.190523f,-0.966478f, -0.749349f,-0.631084f,-0.200524f, -0.0839644f,-0.7029f,-0.706316f, -0.846688f,0.428738f,-0.315124f, -0.582476f,0.748204f,0.317668f, 0.132445f,0.890966f,0.434325f, 0.0422852f,-0.606583f,-0.793895f, -0.891776f,0.0801057f,-0.445329f, -0.169034f,-0.251967f,0.952859f, -0.880026f,-0.439568f,-0.179817f, 0.204542f,-0.597438f,-0.775391f, 0.534385f,0.787107f,0.308051f, 0.546123f,0.34151f,0.764932f, 0.251391f,-0.963661f,0.0903392f, -0.236755f,0.418064f,-0.877023f, -0.599523f,0.411853f,-0.686257f, 0.859044f,-0.129168f,0.495337f, -0.045998f,0.118155f,-0.991929f, 0.512858f,-0.718741f,0.469455f, 0.7516f,0.623059f,-0.216554f, 0.710471f,0.39301f,-0.583758f, 0.620056f,-0.782698f,0.0539844f, 0.409139f,0.481193f,0.77528f, -0.0245102f,0.763395f,0.645467f, -0.617738f,-0.786136f,0.0197439f, 0.291845f,0.952936f,-0.0821005f, -0.229211f,0.296339f,-0.927171f, -0.969165f,-0.237308f,-0.0663659f, 0.44145f,-0.481374f,-0.757232f, -0.187159f,-0.331969f,0.924537f, -0.961305f,0.272517f,-0.040332f, 0.10673f,-0.993094f,-0.0487087f, -0.306204f,0.767519f,-0.563164f, -0.0416648f,0.161502f,-0.985993f, -0.757445f,0.286696f,0.586585f, -0.215819f,0.0147139f,0.976322f, 0.33691f,0.18853f,0.922468f, 0.998583f,0.0222833f,-0.0483307f, 0.961765f,0.161074f,-0.221502f, 0.294182f,-0.284631f,0.912383f, -0.664656f,-0.231643f,0.710334f, -0.544217f,0.234206f,0.80559f, -0.423324f,-0.538315f,0.728707f, -0.565213f,-0.788506f,-0.242471f, -0.213138f,-0.894246f,0.393568f, -0.130494f,-0.751839f,-0.646305f, 0.958268f,0.239876f,-0.155505f, 0.290058f,-0.823204f,0.488058f, 0.309625f,0.928692f,-0.204118f, 0.285388f,0.209678f,-0.935195f, 0.624958f,0.774744f,-0.095911f, -0.720927f,-0.673241f,0.164351f, 0.200143f,0.582396f,0.787882f, 0.709433f,0.70174f,-0.0653112f, 0.669754f,-0.142254f,0.72883f, -0.599268f,0.426455f,-0.677506f, -0.642151f,-0.532336f,0.551598f, -0.189632f,-0.824074f,0.5338f, 0.562871f,0.188189f,-0.804836f, 0.149933f,-0.619419f,-0.77061f, 0.336407f,0.767599f,-0.545547f, -0.517906f,0.850619f,0.0906704f, -0.414094f,0.398082f,0.81857f, -0.516187f,0.645454f,0.562974f, -0.524015f,0.109885f,-0.844591f, -0.368867f,0.162392f,-0.915186f, -0.485972f,0.498977f,-0.717532f, 0.886963f,-0.272953f,0.372551f, -0.605056f,-0.366342f,0.706895f, 0.169401f,-0.695185f,0.698585f, 0.0332623f,-0.781223f,0.623366f, 0.921565f,-0.208774f,0.327311f, -0.716401f,0.169703f,-0.676735f, 0.795758f,-0.565624f,0.216424f, -0.823709f,0.296251f,-0.483465f, 0.775355f,-0.631177f,-0.0209815f, 0.853316f,-0.521369f,0.00515418f, 0.868899f,0.493962f,0.0318651f, -0.863028f,-0.41403f,0.289417f, -0.694045f,-0.454706f,0.558162f, 0.823619f,0.156086f,0.545242f, -0.483097f,-0.547453f,0.68331f, -0.717736f,0.513161f,-0.470659f, -0.602728f,-0.79768f,0.020636f, -0.0745711f,0.799712f,0.595734f, -0.796636f,-0.604176f,-0.0185038f, -0.624775f,0.62701f,0.465311f, 0.746128f,-0.215432f,-0.629985f, 0.583907f,-0.694087f,-0.421066f, -0.249173f,-0.530496f,0.810239f, 0.447868f,-0.404453f,0.797391f, -0.601912f,0.70342f,-0.378024f, 0.503597f,-0.7666f,-0.39839f, -0.0432977f,-0.917327f,0.395773f, 0.561908f,0.827107f,-0.0124098f, 0.274627f,-0.773509f,-0.571195f, -0.100463f,0.984973f,0.140485f, -0.306033f,-0.373382f,0.875745f, -0.189793f,0.347416f,-0.918303f, 0.684423f,-0.358441f,-0.63489f, 0.154625f,-0.410088f,-0.898843f, 0.0837662f,0.979523f,-0.183079f, 0.983055f,0.0927441f,0.158117f, 0.377514f,-0.0897554f,-0.921644f, 0.474456f,-0.785498f,0.397348f, 0.946791f,0.17966f,0.267038f, -0.372675f,-0.635225f,-0.676464f, -0.762694f,-0.645571f,0.0391895f, 0.472626f,0.369202f,-0.800197f, -0.212122f,0.521412f,-0.826519f, -0.669931f,0.549606f,0.499126f, 0.756469f,-0.142304f,0.638361f, 0.473611f,-0.338072f,0.813265f, 0.395505f,-0.243256f,0.885665f, 0.0776741f,0.971174f,-0.225362f, -0.885607f,0.446235f,-0.128746f, -0.210676f,-0.0709873f,-0.974975f, -0.462695f,-0.854613f,-0.235689f, -0.592331f,0.746312f,-0.303583f, -0.425337f,0.904805f,-0.0203828f, 0.608561f,0.525098f,0.594917f, 0.0649888f,0.996097f,0.0597284f, -0.362816f,-0.269801f,0.891949f, -0.766185f,0.621968f,-0.161605f, 0.939575f,-0.332882f,-0.0799323f, -0.599137f,0.617999f,0.50903f, -0.969796f,-0.117412f,-0.213801f, 0.754161f,-0.64183f,-0.138905f, -0.334144f,0.0590088f,0.940673f, 0.525938f,-0.250542f,-0.812784f, -0.712644f,-0.427926f,-0.555894f, -0.403908f,-0.690779f,0.599735f, 0.144041f,-0.270566f,-0.951864f, -0.0660092f,-0.876307f,-0.477209f, 0.104023f,-0.181341f,-0.977903f, 0.48906f,-0.821429f,-0.293384f, 0.959549f,-0.169572f,0.224747f, -0.795625f,0.301403f,0.525487f, -0.575123f,0.565714f,-0.590933f, 0.113588f,-0.989182f,0.0928245f, -0.554664f,-0.362418f,-0.749f, 0.437753f,0.898232f,-0.039403f, 0.647599f,0.0590156f,0.759693f, 0.406042f,0.644981f,-0.647403f, 0.728992f,0.129812f,-0.672101f, 0.397173f,0.895858f,-0.199226f, -0.582126f,-0.736476f,0.344575f, -0.359194f,0.89073f,0.278532f, 0.348287f,0.833668f,-0.428596f, -0.90668f,0.35291f,0.231055f, -0.498184f,-0.67272f,-0.547047f, -0.518101f,0.854275f,-0.0422483f, 0.00640995f,0.436793f,0.899539f, 0.694356f,-0.462493f,-0.551335f, 0.585998f,-0.0415081f,0.809249f, 0.229142f,-0.522038f,-0.821566f, 0.505374f,0.576399f,0.642154f, -0.881574f,0.364751f,0.299639f, 0.0787948f,-0.940785f,-0.32972f, 0.231267f,0.886991f,0.399704f, 0.246038f,-0.967404f,-0.0599558f, 0.976604f,0.156829f,-0.147137f, -0.175935f,-0.887357f,-0.426197f, -0.0888067f,0.814826f,-0.572863f, -0.504073f,0.780714f,-0.369319f, 0.427769f,-0.733496f,-0.528203f, -0.726317f,0.686261f,-0.0388486f, 0.179081f,-0.588791f,0.788197f, -0.394133f,-0.853582f,-0.340671f, 0.78888f,-0.377468f,-0.48496f, -0.0520013f,-0.383562f,-0.92205f, -0.893324f,0.0747461f,0.443153f, -0.947471f,-0.267776f,-0.174912f, 0.372373f,0.16703f,0.912929f, 0.576746f,-0.185424f,0.795601f, -0.209963f,0.825562f,0.523797f, 0.531386f,-0.847062f,0.0106966f, 0.660144f,0.407805f,0.630797f, 0.732455f,-0.363599f,0.575592f, 0.291914f,-0.825468f,0.483104f, -0.439027f,0.722985f,0.53343f, -0.594867f,0.790935f,0.143369f, 0.145116f,0.925241f,0.350529f, 0.832664f,-0.0850836f,-0.547203f, -0.138171f,0.773721f,0.618276f, -0.43245f,-0.753266f,-0.495558f, 0.675908f,-0.661027f,-0.32587f, 0.0922018f,-0.326303f,-0.940758f, 0.854707f,-0.515165f,-0.063882f, 0.352314f,0.562006f,-0.748348f, -0.257888f,0.827191f,0.499248f, -0.238609f,-0.950512f,-0.198981f, 0.467982f,-0.33159f,-0.819171f, 0.316668f,-0.789939f,0.525088f, 0.552343f,0.707906f,0.440211f, -0.25786f,0.758563f,-0.598407f, 0.980166f,0.131264f,0.148473f, -0.079118f,-0.976546f,0.200246f, 0.987954f,0.014368f,0.154078f, 0.408421f,0.813886f,0.413256f, 0.752302f,0.657332f,0.0442238f, -0.463284f,-0.769919f,0.438854f, 0.568243f,0.0029728f,-0.822855f, 0.031022f,-0.130467f,0.990967f, 0.990519f,-0.0387556f,-0.131794f, 0.994624f,0.0889935f,-0.0529504f, 0.741371f,-0.564076f,0.363576f, -0.666811f,0.0515178f,0.743444f, -0.179059f,0.431022f,0.884397f, -0.116988f,0.454373f,0.883096f, -0.856769f,0.392163f,0.334895f, 0.0544791f,-0.336532f,-0.940095f, -0.576917f,0.163969f,-0.800176f, -0.753161f,0.657624f,0.0167232f, -0.732521f,-0.00145441f,-0.680743f, 0.68194f,-0.730721f,-0.0317004f, -0.59717f,-0.10676f,0.794978f, 0.815561f,-0.551797f,0.174299f, -0.0578817f,-0.57246f,-0.817887f, -0.539934f,0.835346f,-0.103292f, -0.946983f,-0.11916f,0.298369f, -0.462059f,-0.739832f,0.48903f, 0.136157f,-0.758952f,0.636752f, 0.634623f,-0.217618f,-0.741549f, -0.665494f,0.0943016f,0.740422f, -0.921073f,0.134383f,0.365466f, -0.294704f,-0.226159f,-0.92844f, 0.427131f,-0.494603f,-0.756919f, -0.258123f,-0.177861f,-0.949599f, 0.814817f,-0.184763f,0.549487f, -0.56051f,-0.76659f,0.313319f, 0.0280009f,-0.996343f,-0.0807278f, 0.0150423f,-0.648973f,0.760663f, 0.717395f,-0.399097f,0.571022f, -0.477909f,-0.0825125f,-0.874526f, 0.803847f,-0.468609f,-0.366382f, 0.284638f,-0.350154f,0.892397f, -0.538295f,-0.811046f,0.229005f, 0.969519f,-0.0947611f,-0.225949f, -0.248168f,-0.959276f,-0.134912f, -0.97322f,0.227646f,-0.0319455f, -0.923528f,-0.376292f,-0.0741714f, -0.0776691f,0.348394f,-0.934125f, -0.633594f,0.57028f,0.522819f, -0.647006f,0.747056f,0.152613f, -0.379962f,-0.856087f,0.350349f, -0.530126f,-0.740667f,0.41277f, 0.692724f,-0.31589f,0.648342f, 0.443442f,-0.807031f,0.38995f, -0.61987f,-0.217277f,-0.754024f, 0.155454f,-0.779508f,-0.606796f, -0.446471f,0.196781f,-0.872892f, 0.465126f,-0.875732f,0.129422f, -0.474305f,-0.860205f,-0.187301f, -0.266405f,-0.809338f,0.523451f, -0.483479f,-0.822591f,0.299321f, -0.526938f,0.778557f,-0.340861f, 0.0264823f,0.599695f,-0.79979f, -0.221466f,-0.844942f,-0.486854f, -0.80323f,-0.0665852f,0.591935f, -0.940704f,0.332401f,0.0677124f, 0.730779f,0.419274f,-0.538676f, 0.642794f,0.0477978f,0.764546f, 0.506012f,0.819022f,-0.270472f, 0.130599f,-0.862353f,0.489173f, 0.75464f,0.548181f,0.360579f, -0.884918f,-0.403512f,0.232589f, 0.405047f,0.656485f,-0.636368f, -0.866232f,-0.0349065f,0.498421f, -0.583675f,-0.811932f,-0.00947614f, 0.800791f,-0.594164f,-0.0755191f, 0.332112f,-0.913002f,-0.236915f, -0.0153234f,-0.648054f,-0.76144f, 0.587377f,-0.547668f,0.595859f, 0.89209f,-0.184112f,-0.412648f, -0.0953723f,0.941601f,-0.322941f, 0.622127f,0.763271f,-0.174286f, 0.909725f,0.380148f,0.166996f, -0.610757f,0.67078f,-0.42075f, -0.954538f,-0.296097f,-0.0344094f, 0.422611f,0.692227f,0.584997f, 0.108521f,-0.117612f,-0.987112f, 0.903547f,-0.195479f,0.381301f, -0.547486f,0.584017f,0.599319f, 0.707394f,-0.0437245f,0.705466f, 0.10611f,-0.849294f,-0.517146f, 0.333394f,-0.816065f,-0.472108f, 0.575538f,0.810974f,0.105254f, 0.558157f,-0.683741f,0.470063f, 0.260697f,-0.846188f,0.464761f, 0.315701f,-0.492848f,-0.810823f, 0.0823766f,-0.985902f,-0.145641f, -0.296834f,0.832358f,-0.468048f, 0.851573f,-0.089689f,0.516506f, -0.940818f,-0.2806f,-0.190067f, -0.0330614f,-0.975659f,0.216787f, -0.716925f,0.486958f,0.498889f, -0.749758f,0.0749932f,-0.657449f, 0.482694f,0.792281f,0.373226f, 0.708469f,0.00198965f,0.705739f, 0.754776f,-0.311541f,-0.577283f, -0.687044f,0.713631f,-0.136756f, 0.233785f,0.956785f,0.172934f, -0.240008f,-0.857947f,0.454229f, 0.542987f,0.40361f,0.736386f, 0.0326531f,0.80638f,0.590495f, -0.333953f,0.560826f,0.757594f, -0.870133f,0.368684f,-0.327017f, 0.745522f,-0.612346f,-0.263115f, 0.953437f,-0.0887491f,-0.288239f, -0.460043f,0.5645f,-0.685346f, -0.836416f,-0.54568f,0.0513966f, 0.647267f,-0.507912f,0.568393f, -0.742267f,0.603927f,-0.290365f, -0.625443f,0.434792f,0.647902f, 0.633467f,0.101981f,0.76702f, 0.615992f,-0.0507071f,-0.786119f, 0.579906f,-0.607729f,0.542563f, 0.21613f,-0.670424f,-0.709803f, -0.395525f,-0.884995f,-0.24565f, 0.0594872f,-0.52731f,-0.847588f, 0.596391f,0.707488f,-0.379182f, -0.12898f,-0.543596f,-0.829378f, 0.681881f,-0.532843f,0.501115f, -0.0256417f,0.830853f,-0.5559f, 0.78813f,0.612637f,-0.0593883f, 0.835888f,0.115652f,-0.536578f, 0.732543f,0.418795f,-0.536648f, 0.977152f,0.209706f,0.0346145f, 0.807478f,0.523963f,0.271003f, -0.493483f,-0.330146f,0.80466f, -0.916436f,-0.0281943f,-0.399187f, 0.592034f,-0.542728f,-0.59577f, -0.261623f,0.569832f,0.779003f, -0.984448f,0.149187f,-0.0927637f, -0.557732f,0.0782083f,-0.826328f, -0.930305f,-0.263576f,0.255067f, -0.903932f,0.422906f,0.0637004f, 0.738728f,0.527805f,-0.419169f, 0.699243f,0.249067f,-0.670093f, -0.692693f,-0.0640905f,-0.718379f, -0.333047f,0.227656f,0.915015f, -0.0416427f,0.85795f,0.512042f, 0.044029f,0.242582f,-0.969131f, -0.343728f,0.587913f,0.732263f, 0.873094f,0.451017f,0.185178f, 0.376186f,-0.913598f,0.154345f, -0.500946f,-0.10413f,0.859192f, -0.168621f,-0.890865f,-0.421813f, -0.119882f,-0.649205f,0.751107f, -0.570847f,-0.572209f,0.588822f, 0.430715f,0.724131f,0.538627f, -0.788098f,0.615472f,-0.00982647f, -0.333001f,-0.441249f,0.833313f, -0.612826f,0.502349f,-0.609992f, 0.392413f,0.85833f,0.330577f, 0.222624f,0.136578f,-0.96529f, -0.987197f,-0.0445472f,-0.153159f, 0.147161f,-0.728027f,-0.669567f, 0.896797f,-0.41804f,0.144904f, -0.984821f,0.146624f,-0.0928957f, -0.552727f,0.406119f,-0.727709f, -0.403452f,0.782982f,0.473461f, 0.240594f,-0.848096f,0.472068f, 0.328828f,0.942943f,-0.0522498f, -0.204184f,-0.646776f,0.73484f, -0.88256f,-0.373287f,0.28591f, -0.645072f,-0.0871545f,0.759135f, -0.613952f,0.735791f,-0.285788f, 0.0290869f,-0.982086f,-0.186176f, -0.91248f,0.299189f,-0.279047f, -0.538195f,0.400479f,0.741595f, 0.414685f,0.833155f,-0.365907f, -0.174274f,0.251532f,-0.95203f, 0.138118f,0.862283f,0.487229f, 0.654917f,-0.717876f,0.23609f, 0.853545f,0.0557131f,-0.518032f, 0.628672f,0.255758f,-0.734411f, -0.631019f,-0.476601f,-0.6121f, 0.380818f,0.924611f,-0.00849564f, 0.830112f,-0.0229129f,-0.557126f, -0.874545f,0.141151f,-0.463948f, 0.233492f,0.961521f,0.144772f, -0.731113f,0.0668069f,0.678978f, -0.586998f,0.56462f,-0.580205f, 0.0477931f,-0.719618f,0.692724f, 0.0676299f,0.767856f,-0.637042f, 0.735073f,0.130282f,-0.665353f, 0.505459f,0.513592f,0.69335f, 0.515906f,0.849061f,-0.11374f, 0.424736f,-0.525125f,0.737457f, 0.782778f,-0.224021f,-0.580581f, -0.0667832f,-0.55466f,-0.829393f, 0.583925f,0.766327f,-0.267906f, -0.604931f,0.746517f,-0.277074f, -0.742788f,-0.235251f,-0.626836f, -0.400067f,0.762207f,0.508907f, -0.00426167f,0.998549f,0.0536775f, -0.785582f,-0.121026f,0.606806f, -0.404355f,-0.913951f,0.0345121f, -0.88368f,0.382322f,-0.270073f, 0.881222f,0.115711f,-0.458321f, -0.701469f,0.630814f,0.331685f, -0.562963f,0.72398f,0.398655f, 0.408996f,-0.515596f,0.752916f, -0.462667f,0.769015f,-0.441083f, -0.579102f,-0.777961f,0.243757f, 0.486669f,0.318986f,-0.813266f, -0.770777f,0.575567f,-0.273177f, 0.660334f,-0.105042f,-0.74359f, -0.660321f,0.0964276f,0.744767f, 0.0783261f,0.919177f,-0.385977f, -0.697285f,-0.3691f,0.614458f, -0.717755f,-0.0418237f,-0.695038f, -0.0947467f,0.03777f,-0.994785f, 0.182742f,-0.675672f,-0.714194f, -0.0131797f,-0.491541f,0.870755f, -0.702374f,0.346641f,-0.6217f, -0.149444f,-0.904169f,-0.400181f, 0.599306f,0.634349f,0.488297f, 0.578358f,0.364206f,0.729969f, 0.0657996f,0.827075f,-0.558227f, -0.121967f,-0.264481f,-0.956647f, 0.732262f,0.615485f,-0.291497f }; /****************************************************************************** ***************************** TYPE DEFINITION ******************************** ******************************************************************************/ /****************************************************************************** ***************************** METHOD DEFINITION ****************************** ******************************************************************************/ /****************************************************************************** * Constructor ******************************************************************************/ PtNoise::PtNoise() { } /****************************************************************************** * Destructor ******************************************************************************/ PtNoise::~PtNoise() { } /****************************************************************************** * Initialize ******************************************************************************/ void PtNoise::initialize() { } /****************************************************************************** * Finalize ******************************************************************************/ void PtNoise::finalize() { } /****************************************************************************** * Evaluate PPTBF ******************************************************************************/ float PtNoise::eval() { // PPTBF value float pptbf = 0.f; return pptbf; }
53,377
C++
.cpp
479
109.256785
214
0.68711
ASTex-ICube/semiproctex
39
8
2
LGPL-2.1
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,901
PtEnvironment.cpp
ASTex-ICube_semiproctex/PPTBF_Structures_Src/PtModel/PtEnvironment.cpp
/* * Publication: Semi-Procedural Textures Using Point Process Texture Basis Functions * Authors: anonymous * * Code author: Pascal Guehl * * anonymous * anonymous */ /** * @version 1.0 */ #include "PtEnvironment.h" /****************************************************************************** ******************************* INCLUDE SECTION ****************************** ******************************************************************************/ /****************************************************************************** ****************************** NAMESPACE SECTION ***************************** ******************************************************************************/ // Project using namespace Pt; /****************************************************************************** ************************* DEFINE AND CONSTANT SECTION ************************ ******************************************************************************/ /****************************************************************************** ***************************** TYPE DEFINITION ******************************** ******************************************************************************/ std::string PtEnvironment::mProgramPath = PT_PROJECT_PATH + std::string( "/" ); std::string PtEnvironment::mWorkingDirectory = PT_PROJECT_PATH + std::string( "/Dev/Install/PPTBFProject/bin/" ); std::string PtEnvironment::mSettingDirectory = PT_PROJECT_PATH + std::string( "/Dev/Install/PPTBFProject/bin/Settings/" ); std::string PtEnvironment::mDataPath = PT_DATA_PATH + std::string( "/" ); std::string PtEnvironment::mShaderPath = PT_SHADER_PATH + std::string( "/" ); std::string PtEnvironment::mImagePath = PT_IMAGE_PATH + std::string( "/" ); /****************************************************************************** ***************************** METHOD DEFINITION ****************************** ******************************************************************************/
2,015
C++
.cpp
36
54.194444
122
0.332487
ASTex-ICube/semiproctex
39
8
2
LGPL-2.1
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,902
PtPPTBFLoader.cpp
ASTex-ICube_semiproctex/PPTBF_Structures_Src/PtModel/PtPPTBFLoader.cpp
/* * Publication: Semi-Procedural Textures Using Point Process Texture Basis Functions * Authors: anonymous * * Code author: Pascal Guehl * * anonymous * anonymous */ /** * @version 1.0 */ #include "PtPPTBFLoader.h" /****************************************************************************** ******************************* INCLUDE SECTION ****************************** ******************************************************************************/ // STL #include <fstream> #include <iostream> #include <algorithm> #include <set> //// Project //#include "PtPPTBF.h" /****************************************************************************** ****************************** NAMESPACE SECTION ***************************** ******************************************************************************/ // Project using namespace Pt; /****************************************************************************** ************************* DEFINE AND CONSTANT SECTION ************************ ******************************************************************************/ /****************************************************************************** ***************************** TYPE DEFINITION ******************************** ******************************************************************************/ /****************************************************************************** ***************************** METHOD DEFINITION ****************************** ******************************************************************************/ /****************************************************************************** * Constructor ******************************************************************************/ PtPPTBFLoader::PtPPTBFLoader() { // Point process PtPPTBF::tilingtype pTilingType = PtPPTBF::REGULAR; pJittering = 0.f; pCellSubdivisionProbability = 0.f; pNbRelaxationIterations = 0; // Window function pCellularToGaussianWindowBlend = 0.f; pCellularWindowNorm = 0.5;; pRectangularToVoronoiShapeBlend = 0.f; pCellularWindowDecay = 1.f; pGaussianWindowDecay = 1.f; pGaussianWindowDecayJittering = 0.f; // Feature function pMinNbGaborKernels = 0; pMaxNbGaborKernels = 0; pFeatureNorm = 0.5f; pGaborStripesFrequency = 4; pGaborStripesCurvature = 0.15f; pGaborStripesOrientation = 0.2f; pGaborStripesThickness = 0.15f; pGaborDecay = 1.f; pGaborDecayJittering = 0.f; pFeaturePhaseShift = 0.f; pBombingFlag = false; // Others pRecursiveWindowSubdivisionProbability = 0.f; pRecursiveWindowSubdivisionScale = 0.5f; // Debug pShowWindow = true; pShowFeature = true; } /****************************************************************************** * Destructor ******************************************************************************/ PtPPTBFLoader::~PtPPTBFLoader() { } /****************************************************************************** * Initialize ******************************************************************************/ void PtPPTBFLoader::initialize() { } /****************************************************************************** * Finalize ******************************************************************************/ void PtPPTBFLoader::finalize() { } /****************************************************************************** * Import ******************************************************************************/ PtPPTBF* PtPPTBFLoader::import( const char* pFilename ) { PtPPTBF* pptbf = new PtPPTBF(); /*char *name;*/ float origpercent; int RESOL; float alpha; float rescalex; float thresh; // point set parameters PtPPTBF::tilingtype tt; float ppointsub; int decalx; int Nx; int nrelax; float jitter; float inorm; float windowblend; float sigwcell; float inorm2; float sigwgauss; float sigwgaussvar; float larp; float pointval; float varpointval; float psubdiv; float sigwcellfact; float sigwgaussfact; float subdivscale; bool bomb; float sigcos; float sigcosvar; int Npmin; int Npmax; int freq; float phase; float thickness; float courbure; float deltaorient; float ampli[3]; char buff[100]; char *str; //sprintf(buff, "%s_params.txt", name); //FILE *fd = fopen(buff, "r"); FILE *fd = fopen( pFilename, "r" ); if (fd == 0) { perror("cannot save parameters file:"); return nullptr; } fscanf(fd, "%s\n", buff); //printf("load data for %s : %s\n", name, buff); printf( "load data for %s : %s\n", pFilename, buff ); //fgets(buff, 100, fd); str = buff; while (*str != '=' && *str!=0) str++; //sscanf(str+1, "%d\n", &RESOL); //fgets(buff, 100, fd); str = buff; while (*str != '=' && *str != 0) str++; //sscanf(str+1, "%f\n", &alpha); //fgets(buff, 100, fd); str = buff; while (*str != '=' && *str != 0) str++; //sscanf(str+1, "%f\n", &rescalex); int type = 0; fgets(buff, 100, fd); str = buff; while (*str != '=' && *str != 0) str++; if (buff[0] != 't' || buff[1] != 'y') printf("incoherent file: %s", buff); sscanf(str+1, "%d\n", &type); if (type <= 2) { tt = PtPPTBF::REGULAR; decalx = 1 + type; Nx = 1; } else if (type ==3) { tt = PtPPTBF::IRREGULAR; decalx = 1 ; Nx = 1; } else if (type==4) { tt = PtPPTBF::IRREGULARX; decalx = 1; Nx = 1; } else if (type == 5) { tt = PtPPTBF::IRREGULARY; decalx = 1; Nx = 1; } else if (type <=8) { tt = PtPPTBF::CROSS; decalx = 1; Nx = type-6+2; } else if (type == 9) { tt = PtPPTBF::BISQUARE; decalx = 1; Nx = 1; } else { tt = PtPPTBF::IRREGULAR; decalx = 1; Nx = 1; } //fgets(buff, 100, fd); str = buff; while (*str != '=' && *str != 0) str++; //sscanf(str+1, "%d\n", &decalx); //fgets(buff, 100, fd); str = buff; while (*str != '=' && *str != 0) str++; //sscanf(str+1, "%d\n", &Nx); fgets(buff, 100, fd); str = buff; while (*str != '=' && *str != 0) str++; if (buff[0] != 'l' || buff[1] != 'a') printf("incoherent file: %s", buff); sscanf(str+1, "%f\n", &larp); fgets(buff, 100, fd); str = buff; while (*str != '=' && *str != 0) str++; if (buff[0] != 'i' || buff[1] != 'n') printf("incoherent file: %s", buff); sscanf(str+1, "%f\n", &inorm ); fgets(buff, 100, fd); str = buff; while (*str != '=' && *str != 0) str++; if (buff[0] != 'i' || buff[1] != 'n') printf("incoherent file: %s", buff); sscanf(str+1, "%f", &inorm2); fgets(buff, 100, fd); str = buff; while (*str != '=' && *str != 0) str++; if (buff[0] != 'n' || buff[1] != 'r') printf("incoherent file: %s", buff); sscanf(str+1, "%d\n", &nrelax); fgets(buff, 100, fd); str = buff; while (*str != '=' && *str != 0) str++; if (buff[0] != 'p' || buff[1] != 's') printf("incoherent file: %s", buff); sscanf(str+1, "%f\n", &psubdiv); fgets(buff, 100, fd); str = buff; while (*str != '=' && *str != 0) str++; sscanf(str+1, "%f\n", &sigwcellfact); fgets(buff, 100, fd); str = buff; while (*str != '=' && *str != 0) str++; sscanf(str+1, "%f\n", &sigwgaussfact); fgets(buff, 100, fd); str = buff; while (*str != '=' && *str != 0) str++; sscanf(str+1, "%f\n", &subdivscale); fgets(buff, 100, fd); str = buff; while (*str != '=' && *str != 0) str++; sscanf(str+1, "%f\n", &ppointsub); fgets(buff, 100, fd); str = buff; while (*str != '=' && *str != 0) str++; sscanf(str+1, "%f\n", &jitter); fgets(buff, 100, fd); str = buff; while (*str != '=' && *str != 0) str++; if (buff[0] != 'w' || buff[1] != 'i') printf("incoherent file: %s", buff); sscanf(str+1, "%f\n", &windowblend); fgets(buff, 100, fd); str = buff; while (*str != '=' && *str != 0) str++; sscanf(str+1, "%f\n", &sigwcell); fgets(buff, 100, fd); str = buff; while (*str != '=' && *str != 0) str++; sscanf(str+1, "%f\n", &sigwgauss); fgets(buff, 100, fd); str = buff; while (*str != '=' && *str != 0) str++; sscanf(str+1, "%f\n", &pointval); fgets(buff, 100, fd); str = buff; while (*str != '=' && *str != 0) str++; sscanf(str+1, "%f\n", &varpointval); fgets(buff, 100, fd); str = buff; while (*str != '=' && *str != 0) str++; sscanf(str+1, "%f\n", &sigwgaussvar); fgets(buff, 100, fd); str = buff; while (*str != '=' && *str != 0) str++; if (buff[0] != 'b' || buff[1] != 'o') printf("incoherent file: %s", buff); if (str[2] != '0' && str[2] != '1') { //hvFatal("incoherent file"); printf( "incoherent file" ); } bomb = (str[2] == '1'); fgets(buff, 100, fd); str = buff; while (*str != '=' && *str != 0) str++; sscanf(str+1, "%d\n", &Npmin); fgets(buff, 100, fd); str = buff; while (*str != '=' && *str != 0) str++; sscanf(str+1, "%d\n", &Npmax); fgets(buff, 100, fd); str = buff; while (*str != '=' && *str != 0) str++; sscanf(str+1, "%f\n", &sigcos); fgets(buff, 100, fd); str = buff; while (*str != '=' && *str != 0) str++; sscanf(str+1, "%f\n", &sigcosvar); fgets(buff, 100, fd); str = buff; while (*str != '=' && *str != 0) str++; sscanf(str+1, "%d\n", &freq); fgets(buff, 100, fd); str = buff; while (*str != '=' && *str != 0) str++; sscanf(str+1, "%f\n", &phase); fgets(buff, 100, fd); str = buff; while (*str != '=' && *str != 0) str++; sscanf(str+1, "%f\n", &thickness); fgets(buff, 100, fd); str = buff; while (*str != '=' && *str != 0) str++; sscanf(str+1, "%f\n", &courbure); fgets(buff, 100, fd); str = buff; while (*str != '=' && *str != 0) str++; sscanf(str+1, "%f\n", &deltaorient); for (int k = 0; k < 3; k++) { fgets(buff, 100, fd); str = buff; while (*str != '=' && *str != 0) str++; sscanf(str+1, "%g", &ampli[k]); } fclose(fd); fd = stdout; //fprintf(fd, "resol = %d\n", RESOL); //fprintf(fd, "alpha = %g\n", alpha); //fprintf(fd, "rescalex = %g\n", rescalex); fprintf(fd, "type = %d\n", (int)tt); fprintf(fd, "decalx = %d\n", decalx); fprintf(fd, "Nx = %d\n", Nx); fprintf(fd, "larp = %g\n", larp); fprintf(fd, "inormc = %g\n", inorm); fprintf(fd, "inormg = %g\n", inorm2); fprintf(fd, "nrelax = %d\n", nrelax); fprintf(fd, "psubdiv = %g\n", psubdiv); fprintf(fd, "sigwcellfact = %g\n", sigwcellfact); fprintf(fd, "sigwgaussfact = %g\n", sigwgaussfact); fprintf(fd, "subdivscale = %g\n", subdivscale); fprintf(fd, "ppointsub = %g\n", ppointsub); fprintf(fd, "jitter = %g\n", jitter); fprintf(fd, "windowblend = %g\n", windowblend); fprintf(fd, "sigwcell = %g\n", sigwcell); fprintf(fd, "sigwgauss = %g\n", sigwgauss); fprintf(fd, "pointval = %g\n", pointval); fprintf(fd, "varpointval = %g\n", 1.0 - pointval); fprintf(fd, "sigwgaussvar = %g\n", sigwgaussvar); fprintf(fd, "Npmin = %d\n", Npmin); fprintf(fd, "Npmax = %d\n", Npmax); fprintf(fd, "sigcos = %g\n", sigcos); fprintf(fd, "sigcosvar = %g\n", sigcosvar); fprintf(fd, "freq = %d\n", freq); fprintf(fd, "phase = %g\n", phase); fprintf(fd, "thickness = %g\n", thickness); fprintf(fd, "courbure = %g\n", courbure); fprintf(fd, "deltaorient = %g\n", deltaorient); for (int k = 0; k < 3; k++) fprintf(fd, "ampli[%d]=%g\n", k, ampli[k]); float norm = PtPPTBF::getNorm(inorm);// < 0.5 ? 1.0f + inorm / 0.5f : 2.0f + pow((inorm - 0.5f) / 0.5f, 0.5f)*50.0f; float norm2 = PtPPTBF::getNorm(inorm2);// < 0.5 ? 1.0f + inorm2 / 0.5f : 2.0f + pow((inorm2 - 0.5f) / 0.5f, 0.5f)*50.0f; //const int HISTOS = 50; //int precision = 40; //hvPict<float> ** pval; //hvPictureMetrics::evalneighbor_pptbf_cell(pval, precision, RESOL, 1, // tt, ppointsub, // decalx, Nx, nrelax, jitter, // norm, windowblend, sigwcell, norm2, sigwgauss, sigwgaussvar, // larp, pointval, varpointval, // psubdiv, sigwcellfact, sigwgaussfact, subdivscale, // bomb, sigcos, sigcosvar, // Npmin, Npmax, freq, phase, thickness, courbure, deltaorient, ampli); //float histosample[HISTOS]; //hvPictureMetrics::histogramm(pval, precision, histosample, HISTOS, 0.0, 1.5f); //thresh = hvPictureMetrics::computeThresh(1.0f - origpercent, histosample, HISTOS, 0.0f, 1.5f); ////thresh = hvPictureMetrics::computeThresh(1.0f - percent, histosample, HISTOS, 0.0f, 1.5f); thresh = hvPictureMetrics::computeThresh(1.0f - featpercent, histosample, HISTOS, 0.0f, 1.5f); //printf("final thresh=%g\n", thresh); //for (int i = 0; i < precision*precision; i++) delete pval[i]; /*char *name;*/ //float origpercent; //int RESOL; float alpha; float rescalex; //float thresh; // point set parameters //int decalx; int Nx; /*float inorm;*/ /*float inorm2;*/ //float pointval; float varpointval; //float sigwcellfact; float sigwgaussfact; // TODO !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! //float ampli[3]; // Point process PtPPTBF::tilingtype pTilingType = tt; pJittering = jitter; pCellSubdivisionProbability = ppointsub; pNbRelaxationIterations = nrelax; // Window function pCellularToGaussianWindowBlend = windowblend; pCellularWindowNorm = norm; pRectangularToVoronoiShapeBlend = larp; pCellularWindowDecay = sigwcell; pGaussianWindowDecay = sigwgauss; // ???????? pGaussianWindowDecayJittering = sigwgaussvar; // ???????? // Feature function pMinNbGaborKernels = Npmin; pMaxNbGaborKernels = Npmax; pFeatureNorm = norm2; pGaborStripesFrequency = freq; pGaborStripesCurvature = courbure; pGaborStripesOrientation = deltaorient; pGaborStripesThickness = thickness; pGaborDecay = sigcos; pGaborDecayJittering = sigcosvar; pFeaturePhaseShift = phase; pBombingFlag = bomb; // Deformation turbulenceA0 = ampli[ 0 ]; turbulenceA1 = ampli[ 1 ]; turbulenceA2 = ampli[ 2 ]; // Others pRecursiveWindowSubdivisionProbability = psubdiv; pRecursiveWindowSubdivisionScale = subdivscale; // Debug pShowWindow = true; pShowFeature = true; return pptbf; } /****************************************************************************** * Write file ******************************************************************************/ void PtPPTBFLoader::write( const PtPPTBF* pDataModel, const char* pFilename) { #if 0 char buff[100]; //sprintf(buff, "%s_params.txt", name); FILE *fd = fopen(buff, "w"); if (fd == 0) { perror("cannot save parameters file:"); return; } //fprintf(fd, "%s\n", name); //fprintf(fd, "resol = %d\n", RESOL); //fprintf(fd, "alpha = %g\n", alpha); //fprintf(fd, "rescalex = %g\n", rescalex); int type = 0; switch (pDataModel->get) { case hvNoise::REGULAR: type = decalx - 1; break; case hvNoise::IRREGULAR: type = 3; break; case hvNoise::IRREGULARX: type = 4; break; case hvNoise::IRREGULARY: type = 5; break; case hvNoise::CROSS: type = 6 + Nx - 2; break; case hvNoise::BISQUARE: type = 9; break; } fprintf(fd, "type = %d\n", type); //fprintf(fd, "decalx = %d\n", decalx); //fprintf(fd, "Nx = %d\n", Nx); fprintf(fd, "larp = %g\n", larp); fprintf(fd, "inormc = %g\n", inorm); fprintf(fd, "inormg = %g\n", inorm2); fprintf(fd, "nrelax = %d\n", nrelax); fprintf(fd, "psubdiv = %g\n", psubdiv); fprintf(fd, "sigwcellfact = %g\n", sigwcellfact); fprintf(fd, "sigwgaussfact = %g\n", sigwgaussfact); fprintf(fd, "subdivscale = %g\n", subdivscale); fprintf(fd, "ppointsub = %g\n", ppointsub); fprintf(fd, "jitter = %g\n", jitter); fprintf(fd, "windowblend = %g\n", windowblend); fprintf(fd, "sigwcell = %g\n", sigwcell); fprintf(fd, "sigwgauss = %g\n", sigwgauss); fprintf(fd, "pointval = %g\n", pointval); fprintf(fd, "varpointval = %g\n", 1.0 - pointval); fprintf(fd, "sigwgaussvar = %g\n", sigwgaussvar); fprintf(fd, "bomb = %d\n", bomb ? 1 : 0); fprintf(fd, "Npmin = %d\n", Npmin); fprintf(fd, "Npmax = %d\n", Npmax); fprintf(fd, "sigcos = %g\n", sigcos); fprintf(fd, "sigcosvar = %g\n", sigcosvar); fprintf(fd, "freq = %d\n", freq); fprintf(fd, "phase = %g\n", phase); fprintf(fd, "thickness = %g\n", thickness); fprintf(fd, "courbure = %g\n", courbure); fprintf(fd, "deltaorient = %g\n", deltaorient); for (int k = 0; k < 3; k++) fprintf(fd, "ampli[%d] = %g\n", k, ampli[k]); fclose(fd); #endif }
15,979
C++
.cpp
361
41.182825
194
0.531272
ASTex-ICube/semiproctex
39
8
2
LGPL-2.1
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,903
PtWindow.cpp
ASTex-ICube_semiproctex/PPTBF_Structures_Src/PtModel/PtWindow.cpp
/* * Publication: Semi-Procedural Textures Using Point Process Texture Basis Functions * Authors: anonymous * * Code author: Pascal Guehl * * anonymous * anonymous */ /** * @version 1.0 */ #include "PtWindow.h" /****************************************************************************** ******************************* INCLUDE SECTION ****************************** ******************************************************************************/ // STL #include <fstream> #include <iostream> #include <algorithm> #include <set> /****************************************************************************** ****************************** NAMESPACE SECTION ***************************** ******************************************************************************/ // Project using namespace Pt; /****************************************************************************** ************************* DEFINE AND CONSTANT SECTION ************************ ******************************************************************************/ /****************************************************************************** ***************************** TYPE DEFINITION ******************************** ******************************************************************************/ /****************************************************************************** ***************************** METHOD DEFINITION ****************************** ******************************************************************************/ /****************************************************************************** * Constructor ******************************************************************************/ PtWindow::PtWindow() { } /****************************************************************************** * Destructor ******************************************************************************/ PtWindow::~PtWindow() { } /****************************************************************************** * Initialize ******************************************************************************/ void PtWindow::initialize() { } /****************************************************************************** * Finalize ******************************************************************************/ void PtWindow::finalize() { }
2,367
C++
.cpp
59
38.372881
84
0.187091
ASTex-ICube/semiproctex
39
8
2
LGPL-2.1
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,904
PtPPTBF.cpp
ASTex-ICube_semiproctex/PPTBF_Structures_Src/PtModel/PtPPTBF.cpp
/* * Publication: Semi-Procedural Textures Using Point Process Texture Basis Functions * Authors: anonymous * * Code author: Pascal Guehl * * anonymous * anonymous */ /** * @version 1.0 */ #include "PtPPTBF.h" /****************************************************************************** ******************************* INCLUDE SECTION ****************************** ******************************************************************************/ // STL #include <fstream> #include <iostream> #include <algorithm> #include <set> #include <cmath> // Project #include "PtWindow.h" #include "PtFeature.h" #include "PtNoise.h" /****************************************************************************** ****************************** NAMESPACE SECTION ***************************** ******************************************************************************/ // Project using namespace Pt; /****************************************************************************** ************************* DEFINE AND CONSTANT SECTION ************************ ******************************************************************************/ /****************************************************************************** ***************************** TYPE DEFINITION ******************************** ******************************************************************************/ /****************************************************************************** ***************************** METHOD DEFINITION ****************************** ******************************************************************************/ float PtPPTBF::getNorm( float inorm ) { return inorm < 0.5f ? 1.0f + std::pow( inorm / 0.5f, 0.2f ) : 2.0f + std::pow( ( inorm - 0.5f ) / 0.5f, 5.0f ) * 50.0f; } /****************************************************************************** * Constructor ******************************************************************************/ PtPPTBF::PtPPTBF() : mWindow( nullptr ) , mFeature( nullptr ) , mNoise( nullptr ) , mWidth( 640 ) , mHeight( 480 ) // Model transform , mResolution( 100 ) , mShiftX( 0.f ) , mShiftY( 0.f ) , mAlpha( 0.f ) , mRescalex( 1.f ) // Deformation , mTurbulenceAmplitude0( 0.f ) , mTurbulenceAmplitude1( 0.f ) , mTurbulenceAmplitude2( 0.f ) // Point process , mTilingType( PtPPTBF::REGULAR ) , mJittering( 0.f ) , mCellSubdivisionProbability( 0.f ) , mNbRelaxationIterations( 0 ) // Window function , mCellularToGaussianWindowBlend( 0.f ) , mCellularWindowNorm( 0.5f ) , mRectangularToVoronoiShapeBlend( 0.f ) , mCellularWindowDecay( 1.f ) , mWindowShape( 0 ) , mWindowArity( 0.f ) , mWindowLarp( 0.f ) , mWindowNorm( 0.f ) , mWindowSmooth( 0.f ) , mWindowBlend( 0.f ) , mWindowSigwcell( 0.f ) , mGaussianWindowDecay( 1.f ) , mGaussianWindowDecayJittering( 0.f ) // Feature function , mMinNbGaborKernels( 0 ) , mMaxNbGaborKernels( 0 ) , mFeatureNorm( 0.5f ) , mGaborStripesFrequency( 4 ) , mGaborStripesCurvature( 0.15f ) , mGaborStripesOrientation( 0.2f ) , mGaborStripesThickness( 0.15f ) , mGaborDecay( 1.f ) , mGaborDecayJittering( 0.f ) , mFeaturePhaseShift( 0.f ) , mBombingFlag( 0 ) // Recursivity , mRecursiveWindowSubdivisionProbability( 0.f ) , mRecursiveWindowSubdivisionScale( 0.5f ) { } /****************************************************************************** * Destructor ******************************************************************************/ PtPPTBF::~PtPPTBF() { } /****************************************************************************** * Initialize ******************************************************************************/ void PtPPTBF::initialize() { mWindow = new PtWindow(); mFeature = new PtFeature(); mNoise = new PtNoise(); } /****************************************************************************** * Finalize ******************************************************************************/ void PtPPTBF::finalize() { delete mWindow; mWindow = nullptr; delete mFeature; mFeature = nullptr; delete mNoise; mNoise = nullptr; } const int MAX_NOISE_RAND = 1024; //static unsigned int P[MAX_NOISE_RAND]; unsigned int P[MAX_NOISE_RAND] = { 673, 514, 228, 3, 157, 394, 315, 202, 123, 20, 606, 878, 605, 77, 926, 117, 581, 850, 1019, 282, 665, 939, 604, 814, 7, 1006, 922, 27, 28, 835, 30, 822, 285, 255, 851, 400, 330, 927, 38, 39, 119, 240, 176, 391, 295, 142, 191, 67, 379, 49, 50, 93, 398, 873, 286, 127, 693, 669, 793, 1020, 559, 278, 140, 410, 430, 411, 46, 47, 736, 13, 481, 160, 246, 772, 318, 82, 367, 660, 78, 291, 863, 445, 727, 483, 745, 968, 622, 894, 838, 661, 90, 91, 335, 700, 94, 994, 549, 97, 945, 161, 486, 340, 8, 418, 104, 303, 344, 232, 588, 45, 503, 615, 284, 787, 71, 728, 544, 691, 762, 149, 634, 452, 996, 203, 505, 178, 58, 638, 220, 260, 130, 139, 934, 16, 958, 631, 194, 967, 511, 195, 441, 181, 1015, 970, 999, 907, 911, 458, 815, 252, 808, 151, 53, 672, 671, 929, 658, 697, 251, 215, 819, 846, 267, 226, 689, 239, 518, 836, 210, 68, 771, 171, 943, 336, 235, 685, 893, 270, 349, 839, 180, 914, 182, 125, 901, 504, 597, 978, 862, 189, 783, 976, 1009, 844, 66, 859, 806, 109, 530, 871, 896, 539, 805, 348, 204, 205, 417, 720, 128, 237, 992, 25, 991, 773, 214, 159, 977, 80, 841, 219, 73, 292, 465, 813, 320, 225, 163, 227, 993, 229, 230, 231, 913, 407, 904, 371, 256, 872, 238, 65, 833, 306, 242, 243, 385, 831, 995, 148, 341, 22, 713, 334, 192, 253, 965, 100, 201, 257, 294, 321, 809, 590, 343, 959, 188, 853, 902, 95, 905, 633, 366, 383, 5, 652, 937, 135, 494, 710, 183, 395, 280, 325, 480, 308, 670, 92, 974, 287, 612, 431, 855, 589, 607, 677, 722, 949, 342, 353, 523, 299, 300, 301, 356, 738, 450, 305, 402, 268, 359, 854, 576, 196, 116, 313, 908, 548, 316, 538, 377, 168, 572, 690, 459, 307, 887, 85, 326, 533, 856, 51, 798, 437, 746, 111, 107, 600, 816, 389, 1022, 382, 743, 567, 358, 528, 923, 439, 323, 223, 103, 373, 350, 351, 32, 776, 397, 29, 245, 715, 216, 442, 766, 361, 521, 19, 912, 224, 427, 752, 368, 234, 254, 174, 546, 478, 363, 208, 34, 74, 378, 155, 447, 463, 425, 384, 108, 566, 721, 150, 388, 337, 825, 37, 989, 915, 261, 279, 675, 885, 666, 596, 903, 401, 571, 24, 852, 657, 75, 169, 36, 409, 990, 560, 786, 1018, 324, 415, 502, 346, 63, 707, 900, 547, 740, 579, 455, 218, 18, 580, 428, 244, 531, 289, 432, 433, 906, 701, 436, 331, 414, 88, 297, 200, 131, 443, 115, 594, 703, 217, 129, 678, 552, 406, 121, 453, 870, 561, 884, 86, 310, 562, 557, 823, 462, 381, 1, 986, 102, 467, 920, 969, 477, 298, 52, 626, 474, 355, 471, 770, 587, 42, 281, 118, 479, 613, 592, 83, 784, 365, 488, 360, 765, 491, 492, 522, 731, 647, 137, 529, 498, 4, 500, 617, 11, 540, 273, 464, 328, 507, 508, 490, 197, 369, 364, 15, 961, 290, 988, 264, 629, 1007, 987, 495, 81, 272, 524, 824, 166, 527, 193, 653, 1008, 880, 532, 889, 69, 535, 536, 812, 723, 712, 955, 422, 542, 718, 637, 954, 510, 421, 794, 236, 120, 868, 412, 608, 277, 79, 556, 555, 309, 403, 213, 434, 212, 898, 973, 493, 732, 35, 170, 569, 570, 725, 57, 709, 769, 938, 472, 619, 578, 761, 515, 802, 749, 352, 910, 698, 302, 956, 435, 399, 623, 444, 10, 136, 473, 779, 262, 405, 598, 526, 475, 897, 602, 739, 879, 370, 283, 271, 944, 89, 610, 792, 599, 429, 639, 132, 616, 803, 618, 936, 59, 259, 33, 925, 696, 250, 734, 627, 724, 826, 630, 628, 152, 985, 877, 635, 222, 101, 892, 960, 591, 931, 187, 456, 834, 916, 646, 54, 789, 179, 680, 651, 1004, 857, 460, 64, 206, 748, 156, 499, 184, 0, 952, 778, 664, 869, 269, 759, 979, 843, 112, 23, 941, 942, 496, 258, 624, 714, 656, 611, 338, 962, 1001, 683, 684, 935, 643, 681, 275, 413, 509, 207, 692, 755, 1011, 860, 818, 122, 70, 828, 662, 21, 84, 470, 963, 705, 550, 380, 387, 154, 764, 96, 339, 575, 733, 449, 317, 717, 788, 497, 134, 512, 781, 767, 393, 867, 241, 1021, 553, 519, 797, 593, 642, 757, 729, 735, 534, 737, 583, 791, 72, 668, 742, 14, 1013, 890, 585, 141, 565, 830, 795, 751, 296, 753, 754, 485, 849, 26, 758, 980, 332, 423, 747, 625, 327, 345, 645, 114, 87, 347, 609, 420, 774, 319, 322, 655, 162, 777, 883, 595, 780, 957, 782, 304, 31, 785, 173, 167, 649, 760, 153, 1012, 614, 948, 886, 601, 796, 730, 997, 799, 659, 333, 489, 874, 804, 667, 875, 807, 790, 933, 810, 848, 506, 60, 487, 586, 372, 817, 636, 221, 98, 821, 554, 708, 876, 964, 124, 165, 469, 829, 704, 248, 641, 741, 543, 288, 858, 953, 147, 454, 840, 12, 76, 190, 461, 845, 837, 847, 44, 891, 687, 158, 516, 265, 199, 482, 1000, 971, 266, 654, 438, 861, 177, 525, 864, 865, 468, 702, 551, 56, 568, 408, 390, 811, 476, 679, 881, 558, 632, 249, 314, 41, 882, 621, 577, 396, 711, 55, 888, 138, 145, 133, 311, 448, 603, 895, 983, 110, 563, 744, 172, 650, 564, 209, 775, 113, 573, 376, 211, 185, 688, 146, 582, 517, 584, 424, 620, 917, 918, 919, 866, 921, 676, 827, 924, 43, 975, 966, 928, 466, 930, 233, 932, 644, 446, 99, 106, 501, 768, 440, 998, 198, 820, 175, 541, 695, 946, 329, 186, 719, 950, 951, 357, 17, 545, 263, 40, 726, 386, 947, 756, 404, 537, 374, 62, 640, 247, 457, 686, 520, 143, 842, 126, 763, 2, 451, 513, 663, 682, 706, 972, 981, 982, 9, 984, 426, 694, 144, 674, 419, 362, 105, 416, 832, 48, 909, 274, 1002, 574, 293, 164, 484, 699, 1003, 312, 354, 276, 801, 648, 940, 1010, 800, 1005, 899, 1014, 61, 1016, 1017, 392, 716, 6, 750, 375, 1023 }; static int phi( int x ) { x = x % MAX_NOISE_RAND; if ( x < 0 ) x = x + MAX_NOISE_RAND; return ( P[ x ] ); } static unsigned int seed; static void seeding(unsigned int x, unsigned int y, unsigned int z) //{ seed=x%unsigned int(1024)+(y%unsigned int(1024))*unsigned int(1024)+(z%unsigned int(1024))*unsigned int(1024*1024); } { seed = phi(x + phi(y + phi(z))) % (unsigned int)(1 << 15) + (phi(3 * x + phi(4 * y + phi(z))) % (unsigned int)(1 << 15))*(unsigned int)(1 << 15); } /****************************************************************************** * Random value between -1.0 and 1.0 ******************************************************************************/ static float next() { seed *= (unsigned int)(3039177861); float res = (float)( ( double(seed) / 4294967296.0 ) * 2.0 - 1.0 ); return res; } /****************************************************************************** * pave() for regular and irregular tilings (REGULAR, IRREGULAR, IRREGULARX, IRREGULARY) * * @param xp x position * @param yp y position * @param Nx used to create a shift on x axis * @param randx * @param randy * @param cx[9] [OUT] 3x3 kernel of point position on x axis * @param cy[9] [OUT] 3x3 kernel of point position on y axis * @param dx[9] [OUT] 3x3 kernel of point distance to border on x axis * @param dy[9] [OUT] 3x3 kernel of point distance to border on y axis ******************************************************************************/ static void pave( const float xp, const float yp, // pavement parameters const int Nx, const float randx, const float randy, float cx[ 9 ], float cy[ 9 ], float dx[ 9 ], float dy[ 9 ] ) { const float x = xp; const float y = yp; // Variables used to pave the plan (floor() and fract()) const int ix = (int)floor( x ); const float xx = x - (float)ix; const int iy = (int)floor( y ); const float yy = y - (float)iy; // Iterate through 3x3 neighborhood (cells) int i, j; int nc = 0; for ( j = -1; j <= +1; j++ ) { for ( i = -1; i <= +1; i++ ) { float rxi, rxs, ryi, rys; // Neighbor cell float ivpx = (float)ix + (float)i; float ivpy = (float)iy + (float)j; // [0;1] float decalx = (float)( (int)ivpy % Nx ) / (float)Nx; // Random point in current cell // [-0.5;0.5] seeding( (unsigned int)( ivpx + 5 ), (unsigned int)( ivpy + 10 ), 0 ); rxi = next() * randx * 0.5f; //printf("rx %d,%d=%g, ", (unsigned int)(ivpx + 5), (unsigned int)(ivpy + 10), rx); // [-0.5;0.5] seeding( 3, (unsigned int)( ivpy + 10 ), 0 ); ryi = next() * randy * 0.5f; // Random point in current cell // [-0.5;0.5] seeding( (unsigned int)( ivpx + 1 + 5 ), (unsigned int)( ivpy + 10 ), 0 ); rxs = next() * randx * 0.5f; //printf("rxs %d,%d=%g\n", (unsigned int)(ivpx +1 + 5), (unsigned int)(ivpy + 10), rxs); // [-0.5;0.5] seeding( 3, (unsigned int)( ivpy + 1 + 10 ), 0 ); rys = next() * randy * 0.5f; // point distance to current rectangular cell border dx[ nc ] = ( 0.5f * ( rxs + 1.0f - rxi ) ); // lies in [0;1] dy[ nc ] = 0.5f * ( rys + 1.0f - ryi ); // lies in [0;1] // point coordinates cx[ nc ] = ( ivpx + decalx + rxi + dx[ nc ] ); cy[ nc ] = ivpy + ryi + dy[ nc ]; // Update counter nc++; } } } /****************************************************************************** * pave() for regular and irregular tilings (REGULAR, IRREGULAR, IRREGULARX, IRREGULARY) * * @param xp x position * @param yp y position * @param Nx used to create a shift on x axis * @param randx * @param randy * @param cx[9] [OUT] 3x3 kernel of point position on x axis * @param cy[9] [OUT] 3x3 kernel of point position on y axis * @param dx[9] [OUT] 3x3 kernel of point distance to border on x axis * @param dy[9] [OUT] 3x3 kernel of point distance to border on y axis ******************************************************************************/ // BISQUARE static void paveb(float x, float y, // pavement parameters float cx[9], float cy[9], float dx[9], float dy[9]) { int i, j; int nc = 0; int ii, jj; int ix = (int)floor(x); float xx = x - (float)ix; int iy = (int)floor(y); float yy = y - (float)iy; int qx = (int)(xx*(int)5); int qy = (int)(yy*(int)5); for (i = 0; i < 3; i++) for (j = 0; j<3; j++) { if (qx >= -2 + i * 2 + j && qx <= -2 + i * 2 + 1 + j && qy >= 1 - i + 2 * j && qy <= 1 - i + 2 * j + 1) { for (ii = 0; ii <= 2; ii++) for (jj = 0; jj <= 2; jj++) { if (i == 1 || j == 1) { int rx = -2 + i * 2 + j - 3 + ii * 2 + jj; int ry = 1 - i + 2 * j - 1 + jj * 2 - ii; dx[nc] = 1.0f / 5.0f; dy[nc] = 1.0f / 5.0f; cx[nc] = (float)ix + (float)rx / 5.0f + 1.0f / 5.0f; cy[nc] = (float)iy + (float)ry / 5.0f + 1.0f / 5.0f; nc++; } } int rx = -2 + i * 2 + j; int ry = 1 - i + 2 * j; dx[nc] = 0.5f / 5.0f; dy[nc] = 0.5f / 5.0f; cx[nc] = (float)ix + (float)(rx - 1) / 5.0f + 0.5f / 5.0f; cy[nc] = (float)iy + (float)ry / 5.0f + 0.5f / 5.0f; nc++; dx[nc] = 0.5f / 5.0f; dy[nc] = 0.5f / 5.0f; cx[nc] = (float)ix + (float)rx / 5.0f + 0.5f / 5.0f; cy[nc] = (float)iy + (float)(ry + 2) / 5.0f + 0.5f / 5.0f; nc++; dx[nc] = 0.5f / 5.0f; dy[nc] = 0.5f / 5.0f; cx[nc] = (float)ix + (float)(rx + 2) / 5.0f + 0.5f / 5.0f; cy[nc] = (float)iy + (float)(ry + 1) / 5.0f + 0.5f / 5.0f; nc++; dx[nc] = 0.5f / 5.0f; dy[nc] = 0.5f / 5.0f; cx[nc] = (float)ix + (float)(rx + 1) / 5.0f + 0.5f / 5.0f; cy[nc] = (float)iy + (float)(ry - 1) / 5.0f + 0.5f / 5.0f; nc++; return; } } for (i = 0; i < 3; i++) for (j = 0; j < 2; j++) { if (qx == i * 2 + j && qy == 2 + 2 * j - i) { dx[nc] = 0.5f / 5.0f; dy[nc] = 0.5f / 5.0f; cx[nc] = (float)ix + (float)qx / 5.0f + dx[nc]; cy[nc] = (float)iy + (float)qy / 5.0f + dy[nc]; nc++; dx[nc] = 0.5f / 5.0f; dy[nc] = 0.5f / 5.0f; cx[nc] = (float)ix + (float)(qx - 2) / 5.0f + dx[nc]; cy[nc] = (float)iy + (float)(qy + 1) / 5.0f + dy[nc]; nc++; dx[nc] = 0.5f / 5.0f; dy[nc] = 0.5f / 5.0f; cx[nc] = (float)ix + (float)(qx + 1) / 5.0f + dx[nc]; cy[nc] = (float)iy + (float)(qy + 2) / 5.0f + dy[nc]; nc++; dx[nc] = 0.5f / 5.0f; dy[nc] = 0.5f / 5.0f; cx[nc] = (float)ix + (float)(qx - 1) / 5.0f + dx[nc]; cy[nc] = (float)iy + (float)(qy - 2) / 5.0f + dy[nc]; nc++; dx[nc] = 0.5f / 5.0f; dy[nc] = 0.5f / 5.0f; cx[nc] = (float)ix + (float)(qx + 2) / 5.0f + dx[nc]; cy[nc] = (float)iy + (float)(qy - 1) / 5.0f + dy[nc]; nc++; dx[nc] = 1.0f / 5.0f; dy[nc] = 1.0f / 5.0f; cx[nc] = (float)ix + (float)(qx - 2) / 5.0f + dx[nc]; cy[nc] = (float)iy + (float)(qy - 1) / 5.0f + dy[nc]; nc++; dx[nc] = 1.0f / 5.0f; dy[nc] = 1.0f / 5.0f; cx[nc] = (float)ix + (float)(qx - 1) / 5.0f + dx[nc]; cy[nc] = (float)iy + (float)(qy + 1) / 5.0f + dy[nc]; nc++; dx[nc] = 1.0f / 5.0f; dy[nc] = 1.0f / 5.0f; cx[nc] = (float)ix + (float)(qx + 1) / 5.0f + dx[nc]; cy[nc] = (float)iy + (float)(qy) / 5.0f + dy[nc]; nc++; dx[nc] = 1.0f / 5.0f; dy[nc] = 1.0f / 5.0f; cx[nc] = (float)ix + (float)(qx) / 5.0f + dx[nc]; cy[nc] = (float)iy + (float)(qy - 2) / 5.0f + dy[nc]; nc++; return; } } printf("error!!!\n"); return; } /****************************************************************************** * pave() for regular and irregular tilings (REGULAR, IRREGULAR, IRREGULARX, IRREGULARY) * * @param xp x position * @param yp y position * @param Nx used to create a shift on x axis * @param randx * @param randy * @param cx[9] [OUT] 3x3 kernel of point position on x axis * @param cy[9] [OUT] 3x3 kernel of point position on y axis * @param dx[9] [OUT] 3x3 kernel of point distance to border on x axis * @param dy[9] [OUT] 3x3 kernel of point distance to border on y axis ******************************************************************************/ // CROSS static void paved(float x, float y, // pavement parameters int Nx, float cx[9], float cy[9], float dx[9], float dy[9]) { int i, j; int ix = (int)floor(x); float xx = x - (float)ix; int iy = (int)floor(y); float yy = y - (float)iy; int qx = (int)(xx*(int)(2 * Nx)); int qy = (int)(yy*(int)(2 * Nx)); // horizontal if ((qx >= qy && qx <= qy + Nx - 1) || (qx >= qy - 2 * Nx && qx <= qy + Nx - 1 - 2 * Nx)) { int rx, ry; if (qx >= qy && qx <= qy + Nx - 1) { rx = qy; ry = qy; } else { rx = qy - 2 * Nx; ry = qy; } for (i = 0; i < 3; i++) { cx[3 * i] = (float)ix + ((float)rx + (float)(i - 1) + (float)(Nx) *0.5f) / (float)(2 * Nx); cy[3 * i] = (float)iy + ((float)ry + (float)(i - 1) + 0.5f) / (float)(2 * Nx); dx[3 * i] = ((float)Nx*0.5f) / (float)(2 * Nx); dy[3 * i] = 0.5f / (float)(2 * Nx); cx[3 * i + 1] = (float)ix + ((float)rx + (float)(i - 2) + 0.5f) / (float)(2 * Nx); cy[3 * i + 1] = (float)iy + ((float)ry + (float)(i - 1) + (float)(Nx) *0.5f) / (float)(2 * Nx); dx[3 * i + 1] = 0.5f / (float)(2 * Nx); dy[3 * i + 1] = ((float)Nx*0.5f) / (float)(2 * Nx); cx[3 * i + 2] = (float)ix + ((float)rx + (float)(i - 1) + (float)Nx + 0.5f) / (float)(2 * Nx); cy[3 * i + 2] = (float)iy + ((float)ry + (float)(i)-(float)(Nx)*0.5f) / (float)(2 * Nx); dx[3 * i + 2] = 0.5f / (float)(2 * Nx); dy[3 * i + 2] = ((float)Nx*0.5f) / (float)(2 * Nx); } } // vertical else { int rx, ry; if (qy >= qx + 1 && qy <= qx + 1 + Nx - 1) { rx = qx; ry = qx + 1; } else { rx = qx; ry = qx + 1 - 2 * Nx; } for (i = 0; i < 3; i++) { cx[3 * i] = (float)ix + ((float)rx + (float)(i - 1) + 0.5f) / (float)(2 * Nx); cy[3 * i] = (float)iy + ((float)ry + (float)(i - 1) + (float)(Nx) *0.5f) / (float)(2 * Nx); dx[3 * i] = 0.5f / (float)(2 * Nx); dy[3 * i] = ((float)Nx*0.5f) / (float)(2 * Nx); cx[3 * i + 1] = (float)ix + ((float)rx + (float)(i - 1) + (float)(Nx)*0.5f) / (float)(2 * Nx); cy[3 * i + 1] = (float)iy + ((float)ry + (float)(i - 2) + 0.5f) / (float)(2 * Nx); dx[3 * i + 1] = ((float)Nx*0.5f) / (float)(2 * Nx); dy[3 * i + 1] = 0.5f / (float)(2 * Nx); cx[3 * i + 2] = (float)ix + ((float)rx + (float)(i - 1) - (float)(Nx)*0.5f) / (float)(2 * Nx); cy[3 * i + 2] = (float)iy + ((float)ry + (float)(i - 1) + (float)(Nx - 1) + 0.5f) / (float)(2 * Nx); dx[3 * i + 2] = ((float)Nx*0.5f) / (float)(2 * Nx); dy[3 * i + 2] = 0.5f / (float)(2 * Nx); } } } /****************************************************************************** * pavement() * * @param x x position * @param y y position * @param tt tiling type * @param decalx * @param Nx * @param ccx [OUT] * @param ccy [OUT] * @param cdx [OUT] * @param cdy [OUT] ******************************************************************************/ static void pavement( const float x, const float y, const PtPPTBF::tilingtype tt, const int decalx, const int Nx, float ccx[ 9 ], float ccy[ 9 ], float cdx[ 9 ], float cdy[ 9 ] ) { switch ( tt ) { case PtPPTBF::REGULAR: pave( x, y, decalx, 0.0f, 0.0f, ccx, ccy, cdx, cdy ); break; case PtPPTBF::IRREGULAR: pave(x, y, decalx, 0.8f, 0.8f, ccx, ccy, cdx, cdy); break; case PtPPTBF::CROSS: paved(x, y, Nx, ccx, ccy, cdx, cdy); break; case PtPPTBF::BISQUARE: paveb(x, y, ccx, ccy, cdx, cdy); break; case PtPPTBF::IRREGULARX: pave(x, y, decalx, 0.8f, 0.0f, ccx, ccy, cdx, cdy); break; case PtPPTBF::IRREGULARY: pave(x, y, decalx, 0.0f, 0.8f, ccx, ccy, cdx, cdy); break; default: pave(x, y, decalx, 0.0f, 0.0f, ccx, ccy, cdx, cdy); break; } } /****************************************************************************** * pointset() * * Point process generation, approximated by non-uniform and irregular grids made of rectangular cells Ri. * * Generated points xi are randomly generated inside cell Ri using jittering amplitude. * The Ri are recursively subdivided, according to a given probability thus generating * clusters of poits instead of uniform distributions. * * Points are generated at current cell plus its 1-neighborhood cells (for next nth-closest point search). * * @param psubx subdivision probality of a cell Ri on x axis * @param psuby subdivision probality of a cell Ri on y axis * @param jitx jittering amplitude on x axis * @param jity jittering amplitude on y axis * @param ccx root/parent cell center on x axis * @param ccy root/parent cell center on y axis * @param cdx root/parent cell's closest distance to border on x axis * @param cdy root/parent cell's closest distance to border on y axis * @param cx [out] list of generated points coordinates on x axis * @param cy [out] list of generated points coordinates on y axis * @param pFeatureCellCenterX [out] list of associated cells centers on x axis * @param pFeatureCellCenterY [out] list of associated cells centers on y axis * @param ndx [out] list of associated cells closest distance to border on x axis * @param ndy [out] list of associated cells closest distance to border on y axis ******************************************************************************/ static int pointset( // point set parameters const float psubx, const float psuby, const float jitx, const float jity, float ccx[9], float ccy[9], float cdx[9], float cdy[9], float cx[100], float cy[100], float pFeatureCellCenterX[100], float pFeatureCellCenterY[100], float ndx[100], float ndy[100] ) { // Loop counter int i, j, k; // Number of randomly generated points (counter) int nc = 0; // Iterate through 3x3 neighborhood cells for ( k = 0; k < 9; k++ ) { // Variables used to pave the plan (floor() and fract()) int ix = (int)floor(ccx[k]); float xx = ccx[k] - (float)ix; int iy = (int)floor(ccy[k]); float yy = ccy[k] - (float)iy; // To decide whether a cell Ri is subdivided or not, we generate a random number in its center and compare it to user "p_sub" // - generate probability [0;1] based on cell center (ccx;ccy) seeding( (unsigned int)((int)floor( ccx[ k ] * 10.0f ) + 10 ), (unsigned int)( (int)floor( ccy[ k ] * 10.0f ) + 3 ), 0 ); float subx = next() * 0.5f + 0.5f; float suby = next() * 0.5f + 0.5f; if ( subx < psubx && suby < psuby ) // Subdivide cell on x axis and y axis { // Cell subdivision on x and y axis // - generate 4 points (1 in each cell) // Random split around cell's center float cutx = 0.5f/*cell center*/ + 0.3f * next() * jitx/*random cut*/; float cuty = 0.5f/*cell center*/ + 0.3f * next() * jity/*random cut*/; float ncdx, ncdy, nccx, nccy, rx, ry; // new cell size (distance from center to border) ncdx = ( cutx * 2.0f * cdx[k] ) * 0.5f; ncdy = ( cuty * 2.0f * cdy[k] ) * 0.5f; // new cell center nccx = ccx[ k ] - cdx[ k ] + ncdx; nccy = ccy[ k ] - cdy[ k ] + ncdy; // Generate random point position in cell // - random amplitude around cell center rx = ncdx * next() * jitx; ry = ncdy * next() * jity; // - random point position cx[ nc ] = nccx + rx; cy[ nc ] = nccy + ry; // Store cell info // - cell center pFeatureCellCenterX[ nc ] = nccx; pFeatureCellCenterY[ nc ] = nccy; // - closest distance to border ndx[ nc ] = ncdx; ndy[ nc ] = ncdy; // Update point counter nc++; ncdx = ((1.0f - cutx)*2.0f*cdx[k])*0.5f; ncdy = (cuty*2.0f*cdy[k])*0.5f; nccx = ccx[k] - cdx[k] + (cutx*2.0f*cdx[k]) + ncdx; nccy = ccy[k] - cdy[k] + ncdy; rx = ncdx * next()*jitx; ry = ncdy * next()*jity; cx[nc] = nccx + rx; cy[nc] = nccy + ry; pFeatureCellCenterX[nc] = nccx; pFeatureCellCenterY[nc] = nccy; ndx[nc] = ncdx; ndy[nc] = ncdy; // Update point counter nc++; ncdx = (cutx*2.0f*cdx[k])*0.5f; ncdy = ((1.0f - cuty)*2.0f*cdy[k])*0.5f; nccx = ccx[k] - cdx[k] + ncdx; nccy = ccy[k] - cdy[k] + (cuty*2.0f*cdy[k]) + ncdy; rx = ncdx * next()*jitx; ry = ncdy * next()*jity; cx[nc] = nccx + rx; cy[nc] = nccy + ry; pFeatureCellCenterX[nc] = nccx; pFeatureCellCenterY[nc] = nccy; ndx[nc] = ncdx; ndy[nc] = ncdy; // Update point counter nc++; ncdx = ((1.0f - cutx)*2.0f*cdx[k])*0.5f; ncdy = ((1.0f - cuty)*2.0f*cdy[k])*0.5f; nccx = ccx[k] - cdx[k] + (cutx*2.0f*cdx[k]) + ncdx; nccy = ccy[k] - cdy[k] + (cuty*2.0f*cdy[k]) + ncdy; rx = ncdx * next()*jitx; ry = ncdy * next()*jity; cx[nc] = nccx + rx; cy[nc] = nccy + ry; pFeatureCellCenterX[nc] = nccx; pFeatureCellCenterY[nc] = nccy; ndx[nc] = ncdx; ndy[nc] = ncdy; // Update point counter nc++; } else if ( subx < psubx ) // Subdivide cell only on x axis { // Cell subdivision on x axis // - generate 2 points (1 in each cell) float cutx = 0.3f + 0.4f*(next()*0.5f + 0.5f); float cuty = 1.0f; float ncdx, ncdy, nccx, nccy, rx, ry; ncdx = (cutx*2.0f*cdx[k])*0.5f; ncdy = (cuty*2.0f*cdy[k])*0.5f; nccx = ccx[k] - cdx[k] + ncdx; nccy = ccy[k] - cdy[k] + ncdy; rx = ncdx * next()*jitx; ry = ncdy * next()*jity; cx[nc] = nccx + rx; cy[nc] = nccy + ry; pFeatureCellCenterX[nc] = nccx; pFeatureCellCenterY[nc] = nccy; ndx[nc] = ncdx; ndy[nc] = ncdy; // Update point counter nc++; ncdx = ((1.0f - cutx)*2.0f*cdx[k])*0.5f; ncdy = (cuty*2.0f*cdy[k])*0.5f; nccx = ccx[k] - cdx[k] + (cutx*2.0f*cdx[k]) + ncdx; nccy = ccy[k] - cdy[k] + ncdy; rx = ncdx * next()*jitx; ry = ncdy * next()*jity; cx[nc] = nccx + rx; cy[nc] = nccy + ry; pFeatureCellCenterX[nc] = nccx; pFeatureCellCenterY[nc] = nccy; ndx[nc] = ncdx; ndy[nc] = ncdy; // Update point counter nc++; } else if ( suby < psuby ) // Subdivide cell only on y axis { // Cell subdivision on y axis // - generate 2 points (1 in each cell) float cutx = 1.0f; float cuty = 0.3f + 0.4f*(next()*0.5f + 0.5f); float ncdx, ncdy, nccx, nccy, rx, ry; ncdx = (cutx*2.0f*cdx[k])*0.5f; ncdy = (cuty*2.0f*cdy[k])*0.5f; nccx = ccx[k] - cdx[k] + ncdx; nccy = ccy[k] - cdy[k] + ncdy; rx = ncdx * next()*jitx; ry = ncdy * next()*jity; cx[nc] = nccx + rx; cy[nc] = nccy + ry; pFeatureCellCenterX[nc] = nccx; pFeatureCellCenterY[nc] = nccy; ndx[nc] = ncdx; ndy[nc] = ncdy; // Update point counter nc++; ncdx = (cutx*2.0f*cdx[k])*0.5f; ncdy = ((1.0f - cuty)*2.0f*cdy[k])*0.5f; nccx = ccx[k] - cdx[k] + ncdx; nccy = ccy[k] - cdy[k] + (cuty*2.0f*cdy[k]) + ncdy; rx = ncdx * next()*jitx; ry = ncdy * next()*jity; cx[nc] = nccx + rx; cy[nc] = nccy + ry; pFeatureCellCenterX[nc] = nccx; pFeatureCellCenterY[nc] = nccy; ndx[nc] = ncdx; ndy[nc] = ncdy; // Update point counter nc++; } else { // No cell subdivision // - generate 1 point in cell float rx = cdx[ k ] * next() * jitx; float ry = cdy[ k ] * next() * jity; cx[ nc ] = ccx[ k ] + rx; cy[ nc ] = ccy[ k ] + ry; pFeatureCellCenterX[nc] = ccx[ k ]; pFeatureCellCenterY[ nc ] = ccy[ k ]; ndx[ nc ] = cdx[ k ]; ndy[ nc ] = cdy[ k ]; // Update point counter nc++; } } // Return number of randomly generated points return nc; } /****************************************************************************** * relax() * * ... ******************************************************************************/ static void relax(int pNbRelaxationIterations, int n, float bx, float by, float dx, float dy, float cx[100], float cy[100], float bcx[100], float bcy[100], float dcx[100], float dcy[100]) { int i, j, k; float mcx[100], mcy[100]; for (i = 0; i < pNbRelaxationIterations; i++) { for (k = 0; k < n; k++) if (cx[k] >= bx - dx && cx[k] <= bx + dx && cy[k] >= by - dy && cy[k] <= by + dy) { float distmin1 = 100000.0; int ind1 = 0; float distmin2 = 100000.0; int ind2 = 0; float distmin3 = 100000.0; int ind3 = 0; for (j = 0; j < n; j++) if (j != k) { float dd = sqrt((cx[k] - cx[j])*(cx[k] - cx[j]) + (cy[k] - cy[j])*(cy[k] - cy[j])); if (dd < distmin1) { distmin3 = distmin2; ind3 = ind2; distmin2 = distmin1; ind2 = ind1; distmin1 = dd; ind1 = j; } else if (dd < distmin2) { distmin3 = distmin2; ind3 = ind2; distmin2 = dd; ind2 = j; } else if (dd < distmin3) { distmin3 = dd; ind3 = j; } } float dx1 = cx[ind1] - cx[k]; float dy1 = cy[ind1] - cy[k]; float no1 = static_cast< float >( sqrt( (double)(dx1*dx1 + dy1*dy1) ) ); if (no1 == 0.0f) no1 = 1.0f; float dx2 = cx[ind2] - cx[k]; float dy2 = cy[ind2] - cy[k]; float no2 = static_cast< float >( sqrt( (double)(dx2*dx2 + dy2*dy2) ) ); if (no2 == 0.0) no2 = 1.0f; float dx3 = cx[ind3] - cx[k]; float dy3 = cy[ind3] - cy[k]; float no3 = static_cast< float >( sqrt( (double)(dx3*dx3 + dy3*dy3) ) ); if (no3 == 0.0) no3 = 1.0f; float dirx = dx1 / no1 / no1 + dx2 / no2 / no2 + dx3 / no3 / no3; float diry = dy1 / no1 / no1 + dy2 / no2 / no2 + dy3 / no3 / no3; float no = sqrt(dirx*dirx + diry*diry); if (no == 0.0) no = 1.0; mcx[k] = cx[k] - (dirx / no * 0.05f); mcy[k] = cy[k] - (diry / no * 0.05f); if (mcx[k] < bcx[k] - dcx[k] + 0.05f) mcx[k] = bcx[k] - dcx[k] + 0.05f; if (mcx[k] > bcx[k] + dcx[k] - 0.05f) mcx[k] = bcx[k] + dcx[k] - 0.05f; if (mcy[k] < bcy[k] - dcy[k] + 0.05f) mcy[k] = bcy[k] - dcy[k] + 0.05f; if (mcy[k] > by + dy) mcy[k] = bcy[k] + dcy[k] - 0.05f; } else { mcx[k] = cx[k]; mcy[k] = cy[k]; } for (k = 0; k < n; k++) { cx[k] = mcx[k]; cy[k] = mcy[k]; } } } /****************************************************************************** * distributeElements() * * Distribution of elements: spatial point process. * * @param pFeaturePointX current x position * @param pFeaturePointY current y position * @param tt tiling type * @param psubx subdivision probability of a rectangular cell along x axis [0;1] * @param psuby subdivision probability of a rectangular cell along y axis [0;1] * @param decalx * @param Nx * @param pNbRelaxationIterations number of iteration of Llyod relaxation algorithm (for repulsive force) * @param pJittering jittering: amplitude of distance in [0;1] to generate position in cells around their center * @param cx [out] list of generated points coordinates on x axis * @param cy [out] list of generated points coordinates on y axis * @param pFeatureCellCenterX [out] list of associated cells centers on x axis * @param pFeatureCellCenterY [out] list of associated cells centers on y axis * @param ndx [out] list of associated cells closest distance to border on x axis * @param ndy [out] list of associated cells closest distance to border on y axis ******************************************************************************/ static int distributeElements( const float pFeaturePointX, const float pFeaturePointY, // point set parameters const PtPPTBF::tilingtype tt, const float psubx, const float psuby, const int decalx, const int Nx, const int pNbRelaxationIterations, const float pJittering, float cx[ 100 ], float cy[ 100 ], float pFeatureCellCenterX[ 100 ], float pFeatureCellCenterY[ 100 ], float ndx[ 100 ], float ndy[ 100 ] ) { // Loop counters int i, k; float ccx[ 9 ]; float ccy[ 9 ]; float cdx[ 9 ]; float cdy[ 9 ]; // Retrieve plan pavement of 1-neighborhood (i.e. tiling of rectangular cells Ri) // cc: cells centers // cd: associated closest distances to cell borders pavement( pFeaturePointX, pFeaturePointY, tt, decalx, Nx, ccx, ccy, // OUT: cells centers of 1-neighborhood cells cdx, cdy ); // OUT: closest distances to borders of 1-neighborhood cells ////---------------------------------- //for ( int i = 0; i < 9; i++ ) //{ // printf( "PAVEMENT: (%f;%f) (%f;%f)\n", ccx[i], ccy[i], cdx[i], cdy[i] ); //} ////---------------------------------- int np = 0; // Check whether or not to apply relaxation (i.e. add repulsive force) if ( pNbRelaxationIterations == 0 ) { // Point process generation, approximated by non-uniform and irregular grids made of rectangular cells Ri. // Generated points xi are randomly generated inside cell Ri using jittering amplitude. // The Ri are recursively subdivided, according to a given probability thus generating // clusters of poits instead of uniform distributions. // Points are generated at current cell plus its 1-neighborhood cells(for next nth - closest point search). np = pointset( psubx, psuby, 0.8f, 0.8f, // jittering ccx, ccy, // cells centers of 1-neighborhood cells cdx, cdy, // closest distances to borders of 1-neighborhood cells cx, cy, // OUT pFeatureCellCenterX, pFeatureCellCenterY, // OUT ndx, ndy ); // OUT } else { for ( k = 0; k < 9; k++ ) { float gccx[ 9 ]; float gccy[ 9 ]; float gcdx[ 9 ]; float gcdy[ 9 ]; float gcx[ 100 ]; float gcy[ 100 ]; float gncx[ 100 ]; float gncy[ 100 ]; float gndx[ 100 ]; float gndy[ 100 ]; pavement( ccx[k], ccy[k], tt, decalx, Nx, gccx, gccy, gcdx, gcdy ); int npk = pointset( psubx, psuby, 0.8f, 0.8f, gccx, gccy, gcdx, gcdy, gcx, gcy, gncx, gncy, gndx, gndy ); relax( pNbRelaxationIterations, npk, ccx[k], ccy[k], cdx[k], cdy[k], gcx, gcy, gncx, gncy, gndx, gndy ); for ( i = 0; i < npk; i++ ) { if ( gcx[i] >= ccx[k] - cdx[k] && gcx[i] <= ccx[k] + cdx[k] && gcy[i] >= ccy[k] - cdy[k] && gcy[i] <= ccy[k] + cdy[k] ) { cx[np] = gcx[i]; cy[np] = gcy[i]; pFeatureCellCenterX[np] = gncx[i]; pFeatureCellCenterY[np] = gncy[i]; ndx[np] = gndx[i]; ndy[np] = gndy[i]; np++; } } } } // Blend randomly generated point positions with their associated cell centers // - with jittering: we use pure random points // - without jittering: we use cells centers // Iterate through poinset for ( i = 0; i < np; i++ ) { // Blend between point and its center cell cx[ i ] = cx[ i ] * pJittering + pFeatureCellCenterX[ i ] * ( 1.0f - pJittering ); cy[ i ] = cy[ i ] * pJittering + pFeatureCellCenterY[ i ] * ( 1.0f - pJittering ); } // return nb points in poinset (between 9 and 9*4) return np; } /****************************************************************************** * cdistance() * * Computer closest distance to cell border the point lies in. * Smooth blend between rectangular cell shapes and p-norm Voronoï cell shapes. * * @param x1 current point position on x axis * @param y1 current point position on y axis * @param x2 feature point position on x axis * @param y2 feature point position on y axis * @param pCellularWindowNorm p-norm used for Voronoi cell shapes * @param cx current cell's center position on x axis * @param cy current cell's center position on y axis * @param dx current cell's closest distance to border on x axis * @param dy current cell's closest distance to border on y axis * @param pRectangularToVoronoiShapeBlend cellular anisotropic distance blend between rectangular cell shapes and p-norm Voronoï cell shapes ******************************************************************************/ static float cdistance( const float x1, const float y1, const float x2, const float y2, const float pCellularWindowNorm, const float cx, const float cy, const float dx, const float dy, const float pRectangularToVoronoiShapeBlend ) { //seeding((unsigned int)(cx*12.0 + 5.0), (unsigned int)(cy*12.0 + 11.0), 0); //float ss = size*next(); // Distance between current point (x1,y1) and feature point (x2,y2) const float ddx = ( x1 - x2 ); const float ddy = ( y1 - y2 ); // normalized rho-norm (rectangular cell shapes) const float ex = ddx < 0.0 ? -ddx / ( x2 - cx + dx ) : ddx / ( cx + dx - x2 ); const float ey = ddy < 0.0 ? -ddy / ( y2 - cy + dy ) : ddy / ( cy + dy - y2 ); //printf("cdist: ddx=%g,ddy=%g, ex=%g, ey=%g, dx=%g,dy=%g\n", ddx, ddy, ex, ey, dx, dy); /*return ( pRectangularToVoronoiShapeBlend * (float)std::pow( std::pow( abs( ddx ), pCellularWindowNorm ) + std::pow( abs( ddy ), pCellularWindowNorm ), 1.0 / pCellularWindowNorm ) + ( 1.0 - pRectangularToVoronoiShapeBlend ) * ( ex > ey ? ex : ey ) );*/ // p-norm (Voronoi cell shapes) const float distanceToVoronoiCell = static_cast< float >( std::pow( std::pow( abs( ddx ), pCellularWindowNorm ) + std::pow( abs( ddy ), pCellularWindowNorm ), 1.0 / pCellularWindowNorm ) ); // normalized rho-norm (rectangular cell shapes) const float distanceToRectangularCell = ( ex > ey ? ex : ey ); // Smooth blend between rectangular cell shapes and p-norm Voronoï cell shapes return ( pRectangularToVoronoiShapeBlend * distanceToVoronoiCell + ( 1.f - pRectangularToVoronoiShapeBlend ) * distanceToRectangularCell ); } /****************************************************************************** * cclosest() * * ... * * @param pRectangularToVoronoiShapeBlend cellular anisotropic distance blend between rectangular cell shapes and p-norm Voronoï cell shapes ******************************************************************************/ static int cclosest(float xx, float yy, float cx[], float cy[], int nc, float pCellularWindowNorm, float cnx[], float cny[], float dx[], float dy[], float pRectangularToVoronoiShapeBlend) { int closestFeatureID = 0; float mind = 0.0; int k; for (k = 0; k < nc; k++) { float dd = cdistance(xx, yy, cx[k], cy[k], pCellularWindowNorm, cnx[k], cny[k], dx[k], dy[k], pRectangularToVoronoiShapeBlend); //float dx = xx - cx[k]; //float dy = yy - cy[k]; //float dd = (float)std::pow(std::pow(abs(dx), pCellularWindowNorm) + std::pow(abs(dy), pCellularWindowNorm), 1.0 / pCellularWindowNorm); if (k == 0) { mind = dd; } else if (mind > dd) { closestFeatureID = k; mind = dd; } } return closestFeatureID; } /****************************************************************************** * celldist() * * ... * * @param pRectangularToVoronoiShapeBlend cellular anisotropic distance blend between rectangular cell shapes and p-norm Voronoï cell shapes ******************************************************************************/ static float celldist(float ixx, float iyy, int k, int closestFeatureID, float cx[], float cy[], int nc, float pCellularWindowNorm, float cnx[], float cny[], float dx[], float dy[], float pRectangularToVoronoiShapeBlend) { float delta = 0.2f; int count, nk; float xx, yy, ddx, ddy, dd; do { xx = ixx; yy = iyy; ddx = cx[k] - xx; ddy = cy[k] - yy; dd = (float)sqrt(ddx*ddx + ddy*ddy); if (dd < 0.001f) return 0.0f; ddx *= delta / dd; ddy *= delta / dd; if (k == closestFeatureID) { ddx = -ddx; ddy = -ddy; } //printf("start with cell %d, %d, %g,%g, %g,%g, %g,%g ->%g,%g\n", k, closestFeatureID, ddx, ddy, ixx, iyy, cx[k], cy[k], xx, yy); //printf("cell is: %g,%g, (%g,%g)\n", cnx[k], cny[k], dx[k], dy[k]); //printf("mincell is: %g,%g, (%g,%g)\n", cnx[closestFeatureID], cny[closestFeatureID], dx[closestFeatureID], dy[closestFeatureID]); count = 0; //nk = cclosest(xx+ddx, yy+ddy, cx, cy, nc, pCellularWindowNorm, cnx, cny, dx, dy, pRectangularToVoronoiShapeBlend); //if (!((k == closestFeatureID && nk == k) || (k != closestFeatureID&&nk != k))) { // printf("start problem with cell, %d, %d, %g,%g, %g,%g, %g,%g ->%g,%g\n", k, closestFeatureID, dx, dy, ixx, iyy, cx[k], cy[k], xx, yy); //} do { xx += ddx; yy += ddy; nk = cclosest(xx, yy, cx, cy, nc, pCellularWindowNorm, cnx, cny, dx, dy, pRectangularToVoronoiShapeBlend); //if (count>97) printf("%d, nk=%d, xx=%g,yy=%g, delta=%g\n", count, nk, xx, yy, delta); count++; } while (((k == closestFeatureID && nk == k) || (k != closestFeatureID&&nk != k)) && count < 100); if (count == 100 && delta <= 0.009) { printf("problem with cell, %d, %d, displ:%g,%g, \nfrom: %g,%g, cell:%g,%g ->at: %g,%g\n", k, closestFeatureID, ddx, ddy, ixx, iyy, cx[k], cy[k], xx, yy); printf("in cell: %g,%g, (%g,%g)\n", cnx[k], cny[k], dx[k], dy[k]); for (int u = 0; u < nc; u++) if (u != k) printf("neighbor cell %d: %g,%g, (%g,%g)\n", u, cnx[u], cny[u], dx[u], dy[u]); //hvFatal("error"); } delta /= 2.0f; } while (count == 100 && delta >= 0.01f); float xa = xx - ddx, ya = yy - ddy; float midx = (xa + xx) / 2.0f, midy = (ya + yy) / 2.0f; //printf("refine ddx=%g, ddy=%g, midx=%g,midy=%g, cx=%g,cy=%g,cnx=%g,cny=%g,dx=%g,dy=%g\n", ddx, ddy, midx, midy, cx[k], cy[k], cnx[k], cny[k], dx[k], dy[k]); for (int i = 0; i < 5; i++) { nk = cclosest(midx, midy, cx, cy, nc, pCellularWindowNorm, cnx, cny, dx, dy, pRectangularToVoronoiShapeBlend); if (((k == closestFeatureID && nk == k) || (k != closestFeatureID&&nk != k))) { xa = midx; ya = midy; } else { xx = midx; yy = midy; } midx = (xa + xx) / 2.0f; midy = (ya + yy) / 2.0f; } float cdi = cdistance(midx, midy, cx[k], cy[k], pCellularWindowNorm, cnx[k], cny[k], dx[k], dy[k], pRectangularToVoronoiShapeBlend); //printf("%g : k=%d, closestFeatureID=%d, ddx=%g, ddy=%g, midx=%g,midy=%g, cx=%g,cy=%g,cnx=%g,cny=%g,dx=%g,dy=%g\n", cdi, k, closestFeatureID, ddx, ddy, midx, midy, cx[k], cy[k], cnx[k], cny[k], dx[k], dy[k]); return cdi; //dx = cx[k] - midx, dy = cy[k] - midy; //return (float)std::pow(std::pow(abs(dx), pCellularWindowNorm) + std::pow(abs(dy), pCellularWindowNorm), 1.0 / pCellularWindowNorm); //return sqrt(dx*dx + dy*dy); } /****************************************************************************** * nthclosest() * * Computer distances to nth-closest points and sort them from closest to farthest. * * @param closestFeatureIDs [OUT] * @param nn * @param xx * @param yy * @param cx * @param cy * @param nc * @param pCellularWindowNorm * @param pFeatureCellCenterX * @param pFeatureCellCenterY * @param dx * @param dy * @param pRectangularToVoronoiShapeBlend ******************************************************************************/ static void nthclosest( int closestFeatureIDs[], int nn, float xx, float yy, float cx[], float cy[], int nc, float pCellularWindowNorm, float pFeatureCellCenterX[], float pFeatureCellCenterY[], float dx[], float dy[], float pRectangularToVoronoiShapeBlend ) { // Loop counter int i, k; float dist[ 200 ]; // Iterate through poinset (elements) for ( k = 0; k < nc; k++ ) { // Compute distance to current point in poinset // Computer closest distance to cell border the point lies in. // Smooth blend between rectangular cell shapes and p-norm Voronoï cell shapes. float dd = cdistance( xx, yy, cx[ k ], cy[ k ], pCellularWindowNorm, pFeatureCellCenterX[ k ], pFeatureCellCenterY[ k ], dx[ k ], dy[ k ], pRectangularToVoronoiShapeBlend ); //float dx = xx - cx[k]; //float dy = yy - cy[k]; //float dd = (float)std::pow(std::pow(abs(dx), pCellularWindowNorm) + std::pow(abs(dy), pCellularWindowNorm), 1.0 / pCellularWindowNorm); dist[ k ] = dd; } // Sort points from closest to farthest for ( i = 0; i < nn; i++ ) { int mk = 0; for ( k = 1; k < nc; k++ ) { if ( dist[ mk ] > dist[ k ] ) { mk = k; } } closestFeatureIDs[ i ] = mk; dist[ mk ] = 100000.0; } } /****************************************************************************** * Evaluate PPTBF ******************************************************************************/ float PtPPTBF::eval( const float x, const float y, // Point process const PtPPTBF::tilingtype pTilingType, const float pJittering, const float pCellSubdivisionProbability, const int pNbRelaxationIterations, // Window function const float pCellularToGaussianWindowBlend, /*const*/ float pCellularWindowNorm, const float pRectangularToVoronoiShapeBlend, const float pCellularWindowDecay, const float pGaussianWindowDecay, const float pGaussianWindowDecayJittering, // Feature function const int pMinNbGaborKernels, const int pMaxNbGaborKernels, /*const*/ float pFeatureNorm, const int pGaborStripesFrequency, const float pGaborStripesCurvature, const float pGaborStripesOrientation, const float pGaborStripesThickness, const float pGaborDecay, const float pGaborDecayJittering, const float pFeaturePhaseShift, const bool pBombingFlag, // Others const float pRecursiveWindowSubdivisionProbability, const float pRecursiveWindowSubdivisionScale, // Debug const bool pShowWindow, const bool pShowFeature ) { // PPTBF value float pptbf = 0.f; // Loop counters int i, k; int decalx = /*tt*/2; int Nx = 1; float featurePointX[ 9 * 4 ], featurePointY[ 9 * 4 ], featureCellCenterX[ 9 * 4 ], featureCellCenterY[ 9 * 4 ], ndx[ 9 * 4 ], ndy[ 9 * 4 ]; // Distribution of elements: spatial point process. // Points are generated for 1-neighborhood (for next stage of nth-closest point search) int nc = distributeElements( x, y, pTilingType, pCellSubdivisionProbability, pCellSubdivisionProbability, decalx, Nx, pNbRelaxationIterations, pJittering, featurePointX, featurePointY, // OUT: list of generated points coordinates featureCellCenterX, featureCellCenterY, // OUT: list of associated cells centers ndx, ndy ); // OUT: list of associated cells closest distance to borders // Clamp max nb of "elements" to 18 int npp = ( nc < 18 ? nc : 18 ); // Compute distances to nth-closest points and sort them from closest to farthest. int closestFeatureIDs[ 20 ]; nthclosest( closestFeatureIDs/*OUT*/, npp, x, y, featurePointX, featurePointY, nc, pCellularWindowNorm, featureCellCenterX, featureCellCenterY, ndx, ndy, pRectangularToVoronoiShapeBlend ); // Closest point float centerx, centery; centerx = featurePointX[ closestFeatureIDs[ 0 ] ]; centery = featurePointY[ closestFeatureIDs[ 0 ] ]; //float inorm = 1.0f; //float inormgauss = 1.0f; float pointvalue; float mval = 1.f; float vval = 0.f; float pmax = -2.0f; //------------------------------------ //params / pptbf_001_0_00_05_0_00_00_00_10_05_20_0 //type = 0 //tt = static_cast< PtPPTBF::tilingtype >( 0 ); //larp = 0; //inorm = 0.5; //inormgauss = 0.5; //nrelax = 0; //pRecursiveWindowSubdivisionProbability = 0; //sigwcellfact = 0.960124; //sigwgaussfact = 0.873739; //pRecursiveWindowSubdivisionScale = 0.520615; //pCellSubdivisionProbability = 0; //jitter = 0; //pCellularToGaussianWindowBlend = 1; //pCellularWindowDecay = 0.945958; //pGaussianWindowDecay = 2; //pGaussianWindowDecayJittering = 0.582092; //pBombingFlag = 0; //pMinNbGaborKernels = 0; //pMaxNbGaborKernels = 0; //pGaborDecay = 1; //pGaborDecayJittering = 0; //pGaborStripesFrequency = 0; //phase = 0; //pGaborStripesThickness = 1; //pGaborStripesCurvature = 0; //pGaborStripesOrientation = 1.5708; /*ampli[0] = 0.0487949; ampli[1] = 0.0461046; ampli[2] = 0.0271428;*/ //pCellularWindowNorm = getNorm( inorm );//<=0.5 ? 1.0f + inorm / 0.5f : 2.0f + std::pow((inorm - 0.5f) / 0.5f, 0.5f)*50.0f; //pFeatureNorm = getNorm( inormgauss ); // <= 0.5 ? 1.0f + inormgauss / 0.5f : 2.0f + std::pow((inormgauss - 0.5f) / 0.5f, 0.5f)*50.0f; //------------------------------------ // Sparse convolution: P x ( F W ) // Iterate through n-th closest points (sorted elements) for ( k = 0; k < npp; k++ ) // for each neighbor cell / point { // Initialize random process based on current point coordinate (k-th closest point) seeding( (unsigned int)( featurePointX[ closestFeatureIDs[ k ] ] * 12.0 + 7.0 ), (unsigned int)( featurePointY[ closestFeatureIDs[ k ] ] * 12.0 + 1.0 ), 0 ); float npointvalue = mval + vval * next(); if ( k == 0 ) { pointvalue = npointvalue; } // float nsig2 = pGaussianWindowDecay + pGaussianWindowDecayJittering * next(); // float subdiv = next() * 0.5f + 0.5f; // float prior = next() * 0.5f + 0.5f; // Number of Gabor kernels const int nbGaborKernels = pMinNbGaborKernels + (int)( (float)( pMaxNbGaborKernels - pMinNbGaborKernels ) * ( 0.5 * next() + 0.5 ) ); if ( nbGaborKernels > 10 ) { printf( "pMinNbGaborKernels=%d, pMaxNbGaborKernels=%d\n", pMinNbGaborKernels, pMaxNbGaborKernels );// hvFatal( "stop" ); } // Compute feature function, by default is constant=1.0 float featureFunction = 1.0; float lx[ 10 ], ly[ 10 ], angle[ 10 ], sigma[ 10 ]; // Initialize Gabor kernels if ( nbGaborKernels > 0 ) // set parameters of cosines { //lx[0] = featurePointX[closestFeatureIDs[k]]; ly[0] = featurePointY[closestFeatureIDs[k]]; angle[0] = pGaborStripesOrientation*next(); //sigma[0] = (pGaborDecay + pGaborDecayJittering*next())*(1.0 + 2.0*(float)nbGaborKernels / 9.0); // Iterate over Gabor kernels for ( i = 0; i < nbGaborKernels; i++ ) { // Random position xj selected inside Ri to get random phase shifts lx[ i ] = featureCellCenterX[ closestFeatureIDs[ k ] ] + next() * pJittering * ndx[ closestFeatureIDs[ k ] ]; ly[ i ] = featureCellCenterY[ closestFeatureIDs[ k ] ] + next() * pJittering * ndy[ closestFeatureIDs[ k ] ]; // Random orientation angle[ i ] = pGaborStripesOrientation * next(); // Random decay sigma[ i ] = ( pGaborDecay + pGaborDecayJittering * next() ) * ( 1.0f + 2.0f * (float)nbGaborKernels / 9.0f ); //if (k==0) printf("n=%d, daa=%g, mdist=%g, x=%g, y=%g\n", i, daa, mdist, lx[i], ly[i]); } } // do sum of cosines if ( nbGaborKernels > 0 && pGaborStripesFrequency >= 0 ) { featureFunction = 0.0; // Iterate through Gabor kernels for ( i = 0; i < nbGaborKernels; i++ ) { // Stretch, rotation float deltax = ( x - lx[ i ] ) / ndx[ closestFeatureIDs[ k ] ]; float deltay = ( y - ly[ i ] ) / ndy[ closestFeatureIDs[ k ] ]; float ddx = pGaborStripesCurvature * ( deltax * cos( -angle[ i ] ) - deltay * sin( -angle[ i ] ) ); float ddy = deltax * sin( -angle[ i ] ) + deltay * cos( -angle[ i ] ); float dd2 = (float)std::pow( std::pow( abs( ddx ), pFeatureNorm ) + std::pow( abs( ddy ), pFeatureNorm ), 1.0 / pFeatureNorm ); const float gaborSinusoidalWave = 0.5f + 0.5f * cos( 2.0f * static_cast< float >( M_PI ) * ( (float)pGaborStripesFrequency ) * dd2 ); const float gaborGaussian = exp( -dd2 * sigma[ i ] ); // beware: gaussian vs RBF !!!! const float gaborKernel = std::pow( gaborSinusoidalWave, 1.0f / pGaborStripesThickness ) * gaborGaussian; featureFunction += gaborKernel; } // Normalization featureFunction /= (float)( nbGaborKernels / 4 > 0 ? nbGaborKernels / 4 : 1 ); if ( featureFunction > 1.0 ) featureFunction = 1.0f; // Add global phase shift to be able to carve patterns in window function W // - apply phase which should be 0.0 or PI/2 featureFunction = featureFunction * cos( pFeaturePhaseShift ) * cos( pFeaturePhaseShift ) + ( 1.0f - featureFunction ) * sin( pFeaturePhaseShift ) * sin( pFeaturePhaseShift ); } // Compute window function: blend between cellular and gaussian // Gaussian // NOTE: erreur !!!!!! gaussian vs radial basis function float ddx = ( x - featurePointX[ closestFeatureIDs[ k ] ] ) / ndx[ closestFeatureIDs[ k ] ]; float ddy = ( y - featurePointY[ closestFeatureIDs[ k ] ] ) / ndy[ closestFeatureIDs[ k ] ]; float sdd = sqrt( ddx * ddx + ddy * ddy ); float gaussianWindow = exp( -nsig2 * sdd ); // cellular float cellularWindow = 0.0f; if ( pCellularToGaussianWindowBlend > 0.05f && k == 0 ) { // LOG //printf("n "); float celldd = celldist(x, y, closestFeatureIDs[k], closestFeatureIDs[0], featurePointX, featurePointY, nc, pCellularWindowNorm, featureCellCenterX, featureCellCenterY, ndx, ndy, pRectangularToVoronoiShapeBlend); float dd = cdistance(x, y, featurePointX[closestFeatureIDs[k]], featurePointY[closestFeatureIDs[k]], pCellularWindowNorm, featureCellCenterX[closestFeatureIDs[k]], featureCellCenterY[closestFeatureIDs[k]], ndx[closestFeatureIDs[k]], ndy[closestFeatureIDs[k]], pRectangularToVoronoiShapeBlend); float dist = celldd < 0.0001f ? 0.0f : dd / (celldd); // Distance is 0 on borders (i.e. inverse of Worley approach) cellularWindow = 1.0f - dist; // LOG //printf("it celldd=%g, dd=%g, dist=%g, cellularWindow=%g\n", celldd, dd,dist,cellularWindow); // Clamp data in [0;1] if ( cellularWindow < 0.0f ) { cellularWindow = 0.0f; } else if ( cellularWindow > 1.0f ) { cellularWindow = 1.0f; } cellularWindow = std::pow( cellularWindow, pCellularWindowDecay ); } // Blend between cellular and gaussian windows float windowFunction = pCellularToGaussianWindowBlend * cellularWindow + ( 1.0f - pCellularToGaussianWindowBlend ) * gaussianWindow; //printf("it k=%d, dd2=%g, cellularWindow =%g, windowFunction=%g, nbGaborKernels=%d, featureFunction=%g\n", k, dd2, cellularWindow,windowFunction,nbGaborKernels, featureFunction); //// TEST -------------------------- //pptbf += windowFunction * featureFunction; // recursive subdivision of the cell for window function only if ( subdiv < pRecursiveWindowSubdivisionProbability ) { float ncenterx, ncentery; /* float ncoeff = eval(x*pRecursiveWindowSubdivisionScale + 10.0*featurePointX[closestFeatureIDs[k]], y*pRecursiveWindowSubdivisionScale + 4.0*featurePointY[closestFeatureIDs[k]], tt, 0.0, decalx, Nx, 0, pJittering, pCellularWindowNorm, pCellularToGaussianWindowBlend, pCellularWindowDecay*sig1fact, pFeatureNorm, pGaborDecay*sig2fact, pGaborDecayJittering*sig2fact, pRectangularToVoronoiShapeBlend, mval, vval, 0.0, 0.0, 0.0, 0.0, false, 0, 0, 0.0, 0.0, 0, 0.0, 0, 1.0, 0.0, ampli, pointvalue, ncenterx, ncentery);*/ //-------------------------- //float ncoeff = 1.f; // TEST !!!!! //-------------------------------------------- float sig1fact = 1.f; float sig2fact = 1.f; //-------------------------------------------- //float ncoeff = eval( x * pRecursiveWindowSubdivisionScale + 10.0 * featurePointX[ closestFeatureIDs[ k ] ], y * pRecursiveWindowSubdivisionScale + 4.0 * featurePointY[ closestFeatureIDs[ k ] ], // pTilingType, 0.0/*ppointsub*/, // decalx, Nx, 0/*nrelax*/, pJittering, // pCellularWindowNorm, pCellularToGaussianWindowBlend, pCellularWindowDecay * sig1fact, // pFeatureNorm, pGaborDecay * sig2fact, pGaborDecayJittering * sig2fact, // pRectangularToVoronoiShapeBlend, // mval, vval, // 0.0/*psubdivcell*/, 0.0/*sig1fact*/, 0.0/*sig2fact*/, 0.0/*subdivscale*/, // false/*bombing*/, // 0/*Npmin*/, 0/*Npmax*/, // 0.0/*sigcos*/, 0.0/*sigcosvar*/, // 0/*freq*/, 0.0/*phase*/, 0/*thickness*/, 1.0/*courbure*/, 0.0/*deltaorient*/, // ampli, // pointvalue, ncenterx, ncentery ); float ncoeff = eval( // Position x * pRecursiveWindowSubdivisionScale + 10.0f * featurePointX[ closestFeatureIDs[ k ] ], y * pRecursiveWindowSubdivisionScale + 4.0f * featurePointY[ closestFeatureIDs[ k ] ], // Point process pTilingType, pJittering, 0.0f/*pCellSubdivisionProbability*/, 0/*pNbRelaxationIterations*/, // Window function pCellularToGaussianWindowBlend, pCellularWindowNorm, pRectangularToVoronoiShapeBlend, pCellularWindowDecay, pGaussianWindowDecay, pGaussianWindowDecayJittering, // Feature function 0/*pMinNbGaborKernels*/, 0/*pMaxNbGaborKernels*/, pFeatureNorm, 0/*pGaborStripesFrequency*/, 1.0f/*pGaborStripesCurvature*/, 0.f/*pGaborStripesOrientation*/, 0/*pGaborStripesThickness*/, pGaborDecay, pGaborDecayJittering, 0.0f/*pFeaturePhaseShift*/, false/*pBombingFlag*/, // Others 0.f/*pRecursiveWindowSubdivisionProbability*/, 0.f/*pRecursiveWindowSubdivisionScale*/, pShowWindow, pShowFeature ); //float PtPPTBF::eval( const float x, const float y, //// Point process //const PtPPTBF::tilingtype pTilingType, const float pJittering, const float pCellSubdivisionProbability, const int pNbRelaxationIterations, //// Window function //const float pCellularToGaussianWindowBlend, /*const*/ float pCellularWindowNorm, const float pRectangularToVoronoiShapeBlend, const float pCellularWindowDecay, const float pGaussianWindowDecay, const float pGaussianWindowDecayJittering, //// Feature function //const int pMinNbGaborKernels, const int pMaxNbGaborKernels, /*const*/ float pFeatureNorm, const int pGaborStripesFrequency, const float pGaborStripesCurvature, const float pGaborStripesOrientation, const float pGaborStripesThickness, const float pGaborDecay, const float pGaborDecayJittering, const float pFeaturePhaseShift, const bool pBombingFlag, //// Others //const float pRecursiveWindowSubdivisionProbability, const float pRecursiveWindowSubdivisionScale ) //-------------------------- // keep min window value if ( windowFunction > ncoeff ) { centerx = ( ncenterx - 10.0f * featurePointX[ closestFeatureIDs[ k ] ] ) / pRecursiveWindowSubdivisionScale; centery = ( ncentery - 4.0f * featurePointY[ closestFeatureIDs[ k ] ] ) / pRecursiveWindowSubdivisionScale; windowFunction = ncoeff; } } // Check whether or not to use bombing if ( pBombingFlag ) { //printf("cell %d: at %g,%g, windowFunction=%g, featureFunction=%g, prior=%g, max=%g\n", k, featurePointX[closestFeatureIDs[k]], featurePointY[closestFeatureIDs[k]], windowFunction, featureFunction, prior, pmax); // add contributions, except if bombing if ( pmax < prior && windowFunction > 0.1f ) { pmax = prior; pptbf = windowFunction * featureFunction; pointvalue = npointvalue; centerx = featurePointX[ closestFeatureIDs[ k ] ]; centery = featurePointY[ closestFeatureIDs[ k ] ]; } } else { if ( ! pShowWindow ) { windowFunction = 1.f; } if ( ! pShowFeature ) { featureFunction = 1.f; } pptbf += windowFunction * featureFunction; } } return pptbf; }
58,548
C++
.cpp
1,330
41.071429
354
0.58924
ASTex-ICube/semiproctex
39
8
2
LGPL-2.1
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,905
PtModelLibrary.cpp
ASTex-ICube_semiproctex/PPTBF_Structures_Src/PtModel/PtModelLibrary.cpp
/* * Publication: Semi-Procedural Textures Using Point Process Texture Basis Functions * Authors: anonymous * * Code author: Pascal Guehl * * anonymous * anonymous */ /** * @version 1.0 */ #include "PtModelLibrary.h" /****************************************************************************** ******************************* INCLUDE SECTION ****************************** ******************************************************************************/ // Project #include "PtEnvironment.h" // STL #include <iostream> // System #include <cassert> // GsGraphics //#include "GsGraphics/GsAssetResourceManager.h" /****************************************************************************** ****************************** NAMESPACE SECTION ***************************** ******************************************************************************/ // Project using namespace Pt; /****************************************************************************** ************************* DEFINE AND CONSTANT SECTION ************************ ******************************************************************************/ /****************************************************************************** ***************************** TYPE DEFINITION ******************************** ******************************************************************************/ bool PtDataModelLibrary::mIsInitialized = false; /****************************************************************************** ***************************** METHOD DEFINITION ****************************** ******************************************************************************/ /****************************************************************************** * Main GsGraphics module initialization method ******************************************************************************/ bool PtDataModelLibrary::initialize( const char* const pWorkingDirectory ) { if ( mIsInitialized ) { return true; } assert( pWorkingDirectory != nullptr ); if ( pWorkingDirectory == nullptr ) { return false; } std::string workingDirectory = std::string( pWorkingDirectory ); const size_t directoryIndex = workingDirectory.find_last_of( "/\\" ); workingDirectory = workingDirectory.substr( 0, directoryIndex ); PtEnvironment::mWorkingDirectory = workingDirectory; PtEnvironment::mSettingDirectory = PtEnvironment::mWorkingDirectory + std::string( "/" ) + std::string( "Settings" ); PtEnvironment::mDataPath = PtEnvironment::mWorkingDirectory + std::string( "/" ) + std::string( "Data" ); PtEnvironment::mShaderPath = PtEnvironment::mDataPath + std::string( "/" ) + std::string( "Shaders/PPTBF" ); PtEnvironment::mImagePath = PtEnvironment::mDataPath + std::string( "/" ) + std::string( "Images" ); // Load plugins //GsAssetResourceManager::get().loadPlugins(""); // Update flag mIsInitialized = true; return true; } /****************************************************************************** * Main GsGraphics module finalization method ******************************************************************************/ void PtDataModelLibrary::finalize() { // Unload plugins //GsAssetResourceManager::get().unloadAll(); // Update flag mIsInitialized = false; }
3,294
C++
.cpp
77
40.792208
118
0.422981
ASTex-ICube/semiproctex
39
8
2
LGPL-2.1
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,906
PtFeature.cpp
ASTex-ICube_semiproctex/PPTBF_Structures_Src/PtModel/PtFeature.cpp
/* * Publication: Semi-Procedural Textures Using Point Process Texture Basis Functions * Authors: anonymous * * Code author: Pascal Guehl * * anonymous * anonymous */ /** * @version 1.0 */ #include "PtFeature.h" /****************************************************************************** ******************************* INCLUDE SECTION ****************************** ******************************************************************************/ // STL #include <fstream> #include <iostream> #include <algorithm> #include <set> /****************************************************************************** ****************************** NAMESPACE SECTION ***************************** ******************************************************************************/ // Project using namespace Pt; /****************************************************************************** ************************* DEFINE AND CONSTANT SECTION ************************ ******************************************************************************/ /****************************************************************************** ***************************** TYPE DEFINITION ******************************** ******************************************************************************/ /****************************************************************************** ***************************** METHOD DEFINITION ****************************** ******************************************************************************/ /****************************************************************************** * Constructor ******************************************************************************/ PtFeature::PtFeature() { } /****************************************************************************** * Destructor ******************************************************************************/ PtFeature::~PtFeature() { } /****************************************************************************** * Initialize ******************************************************************************/ void PtFeature::initialize() { } /****************************************************************************** * Finalize ******************************************************************************/ void PtFeature::finalize() { }
2,374
C++
.cpp
59
38.491525
84
0.189565
ASTex-ICube/semiproctex
39
8
2
LGPL-2.1
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,907
PtImageHelper.cpp
ASTex-ICube_semiproctex/PPTBF_Structures_Src/PtModel/PtImageHelper.cpp
/* * Publication: Semi-Procedural Textures Using Point Process Texture Basis Functions * Authors: anonymous * * Code author: Pascal Guehl * * anonymous * anonymous */ /** * @version 1.0 */ #include "PtImageHelper.h" /****************************************************************************** ******************************* INCLUDE SECTION ****************************** ******************************************************************************/ // stb #define STB_IMAGE_IMPLEMENTATION #define STB_IMAGE_WRITE_IMPLEMENTATION #include <stb_image.h> #include <stb_image_write.h> /****************************************************************************** ****************************** NAMESPACE SECTION ***************************** ******************************************************************************/ /****************************************************************************** ************************* DEFINE AND CONSTANT SECTION ************************ ******************************************************************************/ /****************************************************************************** ***************************** TYPE DEFINITION ******************************** ******************************************************************************/ /****************************************************************************** ***************************** METHOD DEFINITION ****************************** ******************************************************************************/ // Project using namespace Pt; /****************************************************************************** * ... ******************************************************************************/ void PtImageHelper::loadImage( const char* pFilename, int& pWidth, int& pHeight, int& pNrChannels, unsigned char*& pData, int desired_channels ) { stbi_set_flip_vertically_on_load( 1 ); pData = stbi_load( pFilename, &pWidth, &pHeight, &pNrChannels, desired_channels ); } /****************************************************************************** * ... ******************************************************************************/ void PtImageHelper::freeImage( unsigned char* pData ) { // Free memory stbi_image_free( pData ); } /****************************************************************************** * ... ******************************************************************************/ int PtImageHelper::saveImage( const char* pFilename, const int pWidth, const int pHeight, const int pNrChannels, const void* pData ) { const void* data = pData; const int stride_in_bytes = pNrChannels * pWidth; stbi_flip_vertically_on_write( 1 ); int status = stbi_write_png( pFilename, pWidth, pHeight, pNrChannels, data, stride_in_bytes ); return status; }
2,851
C++
.cpp
62
44.16129
144
0.326604
ASTex-ICube/semiproctex
39
8
2
LGPL-2.1
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,908
PtApplication.cpp
ASTex-ICube_semiproctex/PPTBF_Structures_Src/Tools/PtBDDParameterSpaceSampler/PtApplication.cpp
/* * Publication: Semi-Procedural Textures Using Point Process Texture Basis Functions * Computer Graphics Forum (EGSR 2020 special issue) * Authors: P. Guehl , R. AllEgre , J.-M. Dischler, B. Benes , and E. Galin * * Code author: Pascal Guehl */ /** * @version 1.0 */ #include "PtApplication.h" /****************************************************************************** ******************************* INCLUDE SECTION ****************************** ******************************************************************************/ // STL #include <iostream> // Project #include "PtGraphicsPPTBF.h" #include "PtViewer.h" #include <PtModelLibrary.h> #include <PtGraphicsLibrary.h> /****************************************************************************** ****************************** NAMESPACE SECTION ***************************** ******************************************************************************/ // Project using namespace Pt; using namespace PtGraphics; using namespace PtGUI; // STL using namespace std; /****************************************************************************** ************************* DEFINE AND CONSTANT SECTION ************************ ******************************************************************************/ /** * The unique instance of the singleton. */ PtApplication* PtApplication::msInstance = nullptr; /****************************************************************************** ***************************** TYPE DEFINITION ******************************** ******************************************************************************/ /****************************************************************************** ***************************** METHOD DEFINITION ****************************** ******************************************************************************/ /****************************************************************************** * Get the unique instance. * * @return the unique instance ******************************************************************************/ PtApplication& PtApplication::get() { if ( msInstance == nullptr ) { msInstance = new PtApplication(); } return *msInstance; } /****************************************************************************** * Default constructor ******************************************************************************/ PtApplication::PtApplication() : mMainWindow( nullptr ) , mPPTBFParameterFilename() { // User interface mMainWindow = new PtViewer(); } /****************************************************************************** * Destructor ******************************************************************************/ PtApplication::~PtApplication() { // User interface delete mMainWindow; } /****************************************************************************** * Initialize ******************************************************************************/ bool PtApplication::initialize( const char* const pWorkingDirectory ) { bool statusOK = false; statusOK = Pt::PtDataModelLibrary::initialize( pWorkingDirectory ); if ( ! statusOK ) { return false; } statusOK = PtGraphics::PtGraphicsLibrary::initialize( pWorkingDirectory ); if ( ! statusOK ) { return false; } // Initialize the GLFW library initializeGLFW(); // Initialize windows // - at least, create one graphics context initializeWindows(); // Initialize GL library initializeGL(); // Initialize user interface //initializeImGuiUserInterface(); // already done in MainWindow... return true; } /****************************************************************************** * Finalize ******************************************************************************/ void PtApplication::finalize() { // Finalize the GLFW library finalizeGLFW(); } /****************************************************************************** * Initialize GLFW ******************************************************************************/ void PtApplication::initializeGLFW() { // Initialize GLFW library if ( ! glfwInit() ) { // Initialization failed exit( EXIT_FAILURE ); } // Set error callback glfwSetErrorCallback( error_callback ); } /****************************************************************************** * Finalize GLFW ******************************************************************************/ void PtApplication::finalizeGLFW() { glfwTerminate(); } /****************************************************************************** * GLFW error callback ******************************************************************************/ void PtApplication::error_callback( int error, const char* description ) { fprintf( stderr, "Error: %s\n", description ); } /****************************************************************************** * Initialize windows ******************************************************************************/ void PtApplication::initializeWindows() { // Initialize windows mMainWindow->initializeWindow(); } /****************************************************************************** * Initialize GL library ******************************************************************************/ void PtApplication::initializeGL() { // NOTE: the following GLFW functions require a context to be current glfwMakeContextCurrent( mMainWindow->getWindow() ); // Load OpenGL API/extensions gladLoadGLLoader( (GLADloadproc)glfwGetProcAddress ); // Managing swap interval //glfwSwapInterval( 1 ); glfwSwapInterval( 0 ); // Initialize mMainWindow->initializeGL(); } /****************************************************************************** * Initialize ImGui user interface ******************************************************************************/ void PtApplication::initializeImGuiUserInterface() { // Need a GL context? glfwMakeContextCurrent( mMainWindow->getWindow() ); // Initialize ImGui // - GL binding //ImGui_ImplGlfwGL3_Init( mMainWindow->getWindow(), true ); // TODO: check callback: erased/overlapped by ImGui: use custom and call ImGui one !!! () => use FALSE !!!! // - style //ImGui::StyleColorsClassic(); //ImGui::StyleColorsDark(); } /****************************************************************************** * Execute * - main event loop ******************************************************************************/ void PtApplication::execute() { // Set context // NOTE: // By default, making a context non-current implicitly forces a pipeline flush // On machines that support GL_KHR_context_flush_control, you can control whether a context performs this flush by setting the GLFW_CONTEXT_RELEASE_BEHAVIOR window hint. glfwMakeContextCurrent( mMainWindow->getWindow() ); // Handle requests // - data model loading, descriptors computation, texture synthesis, painting, etc... handleRequests(); // Process events glfwPollEvents(); } /****************************************************************************** * Handle requests ******************************************************************************/ void PtApplication::handleRequests() { PtGraphics::PtGraphicsPPTBF* pptbfModel = getPPTBF(); pptbfModel->generateDatabase( mBDDImageWidth, mBDDImageHeight, mBDDImageDirectory.c_str(), mBDDserieID ); } /****************************************************************************** * Post a request ******************************************************************************/ void PtApplication::postRequest( PtPipelineRequest pRequest ) { switch ( pRequest ) { case eLoadDataModel: mOmniScaleModelUpdateRequested = true; break; case eSynthesizeTexture: mTextureSynthesisRequested = true; break; default: break; } } /****************************************************************************** * Get PPTBF ******************************************************************************/ PtGraphicsPPTBF* PtApplication::getPPTBF() { return mMainWindow->getPPTBF(); } /****************************************************************************** * BDD image parameters ******************************************************************************/ void PtApplication::setBDDImageWidth( const int pValue ) { mBDDImageWidth = pValue; } /****************************************************************************** * BDD image parameters ******************************************************************************/ void PtApplication::setBDDImageHeight( const int pValue ) { mBDDImageHeight = pValue; } /****************************************************************************** * BDD image parameters ******************************************************************************/ void PtApplication::setBDDImageDirectory( const char* pPath ) { mBDDImageDirectory = pPath; } /****************************************************************************** * BDD serie ID ******************************************************************************/ void PtApplication::setBDDSerieID( const int pValue ) { mBDDserieID = pValue; } /****************************************************************************** * PPTBF parameters ******************************************************************************/ void PtApplication::setPPTBFParameterFilename( const char* pPath ) { mPPTBFParameterFilename = pPath; }
9,482
C++
.cpp
258
34.825581
170
0.408764
ASTex-ICube/semiproctex
39
8
2
LGPL-2.1
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,909
main.cpp
ASTex-ICube_semiproctex/PPTBF_Structures_Src/Tools/PtBDDParameterSpaceSampler/main.cpp
/* * Publication: Semi-Procedural Textures Using Point Process Texture Basis Functions * Computer Graphics Forum (EGSR 2020 special issue) * Authors: P. Guehl , R. AllEgre , J.-M. Dischler, B. Benes , and E. Galin * * Code author: Pascal Guehl */ /** * @version 1.0 */ /****************************************************************************** ******************************* INCLUDE SECTION ****************************** ******************************************************************************/ // STL #include <iostream> #include <string> // System #include <cstdlib> #include <ctime> // Project #include "PtApplication.h" #include "PtGraphicsPPTBF.h" /****************************************************************************** ****************************** NAMESPACE SECTION ***************************** ******************************************************************************/ /****************************************************************************** ************************* DEFINE AND CONSTANT SECTION ************************ ******************************************************************************/ /****************************************************************************** ***************************** TYPE DEFINITION ******************************** ******************************************************************************/ /****************************************************************************** ***************************** METHOD DEFINITION ****************************** ******************************************************************************/ /****************************************************************************** * Main entry program * * @param pArgc Number of arguments * @param pArgv List of arguments * * @return flag telling whether or not it succeeds ******************************************************************************/ int main( int pArgc, char** pArgv ) { // LOG info std::cout << "-------------------------------------------------------------" << std::endl; std::cout << "- PPTBF Structures BDD Generator on GPU: Command Line Tool --" << std::endl; std::cout << "-------------------------------------------------------------" << std::endl; // Check command line arguments const int nbArguments = 4; if ( pArgc < ( 1 + nbArguments ) ) { std::cout << "ERROR: program requires 4 parameters..." << std::endl; std::cout << "\tprogram width height BDDImageDirectory BDDserieID" << std::endl; // Exit return -1; } // Retrieve program directory int indexParameter = 0; std::string workingDirectory = ""; workingDirectory = pArgv[ indexParameter++ ]; // User customizable parameters : retrieve command line parameters const int BDDImageWidth = std::stoi( pArgv[ indexParameter++ ] ); // default: 4 const int BDDImageHeight = std::stoi( pArgv[ indexParameter++ ] ); // default: 4 const char* BDDImageDirectory = pArgv[ indexParameter++ ]; // default: "../imagestp/many_lichens_on_stone_6040019" const int BDDserieID = std::stoi( pArgv[ indexParameter++ ] ); PtGUI::PtApplication& application = PtGUI::PtApplication::get(); // Initialization application.initialize( workingDirectory.c_str() ); // Set user parameters application.setBDDImageWidth( BDDImageWidth ); application.setBDDImageHeight( BDDImageHeight ); application.setBDDImageDirectory( BDDImageDirectory ); application.setBDDSerieID( BDDserieID ); PtGUI::PtApplication::get().execute(); // LOG info std::cout << "---------------------" << std::endl; std::cout << "- This is the end! --" << std::endl; std::cout << "---------------------" << std::endl; // Finalization application.finalize(); return 0; }
3,770
C++
.cpp
83
43.277108
115
0.437978
ASTex-ICube/semiproctex
39
8
2
LGPL-2.1
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,910
PtViewerConfig.cpp
ASTex-ICube_semiproctex/PPTBF_Structures_Src/Tools/PtBDDParameterSpaceSampler/PtViewerConfig.cpp
/* * Publication: Semi-Procedural Textures Using Point Process Texture Basis Functions * Computer Graphics Forum (EGSR 2020 special issue) * Authors: P. Guehl , R. AllEgre , J.-M. Dischler, B. Benes , and E. Galin * * Code author: Pascal Guehl */ /** * @version 1.0 */ #include "PtViewerConfig.h" /****************************************************************************** ******************************* INCLUDE SECTION ****************************** ******************************************************************************/ /****************************************************************************** ****************************** NAMESPACE SECTION ***************************** ******************************************************************************/ // GsGraphics using namespace Pt; /****************************************************************************** ************************* DEFINE AND CONSTANT SECTION ************************ ******************************************************************************/ /****************************************************************************** ***************************** TYPE DEFINITION ******************************** ******************************************************************************/ //std::string PtEnvironment::mShaderPath = PT_SHADER_PATH + std::string( "/" ); //std::string PtEnvironment::mProgramPath = PT_PROJECT_PATH + std::string( "/" ); //std::string PtEnvironment::mImagePath = PT_IMAGE_PATH + std::string( "/" ); /****************************************************************************** ***************************** METHOD DEFINITION ****************************** ******************************************************************************/ /****************************************************************************** ***************************** METHOD DEFINITION ****************************** ******************************************************************************/
2,047
C++
.cpp
34
58.352941
84
0.248627
ASTex-ICube/semiproctex
39
8
2
LGPL-2.1
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,912
PtViewer.cpp
ASTex-ICube_semiproctex/PPTBF_Structures_Src/Tools/PtBDDParameterSpaceSampler/PtViewer.cpp
/* * Publication: Semi-Procedural Textures Using Point Process Texture Basis Functions * Computer Graphics Forum (EGSR 2020 special issue) * Authors: P. Guehl , R. AllEgre , J.-M. Dischler, B. Benes , and E. Galin * * Code author: Pascal Guehl */ /** * @version 1.0 */ #include "PtViewer.h" /****************************************************************************** ******************************* INCLUDE SECTION ****************************** ******************************************************************************/ // GL #include <glad/glad.h> // STL #include <string> #include <iostream> #include <fstream> // glm //#include <glm/gtc/type_ptr.hpp> // Project #include "PtApplication.h" #include "PtShaderProgram.h" #include "PtPPTBFLoader.h" #include "PtGraphicsPPTBF.h" #include "PtGraphicsHistogram.h" #include <PtEnvironment.h> /****************************************************************************** ****************************** NAMESPACE SECTION ***************************** ******************************************************************************/ // Project using namespace Pt; using namespace PtGraphics; using namespace PtGUI; /****************************************************************************** ************************* DEFINE AND CONSTANT SECTION ************************ ******************************************************************************/ /****************************************************************************** ***************************** TYPE DEFINITION ******************************** ******************************************************************************/ /****************************************************************************** ***************************** METHOD DEFINITION ****************************** ******************************************************************************/ /****************************************************************************** ***************************** METHOD DEFINITION ****************************** ******************************************************************************/ /****************************************************************************** * Default constructor ******************************************************************************/ PtViewer::PtViewer() : mWindow( nullptr ) , mCamera( nullptr ) , mLaunchRequest( false ) , mShowUI( true ) , mGraphicsPPTBF( nullptr ) , mGraphicsHistogram( nullptr ) , mPPTBFUpdateRequested( true ) , mHistogramUpdateRequested( false ) , mUIShowHistogram( false ) , mBinaryStructureMapThreshold( 0.f ) , mUseRealTime( false ) , mGraphicsLBP( nullptr ) , mUseGLCoreProfile( false ) , mGLCoreProfileVAO( 0 ) { uiModelFilename = std::string(); uiTextureSynthesis_launch = false; // PPTBF mGraphicsPPTBF = new PtGraphicsPPTBF(); } /****************************************************************************** * Destructor ******************************************************************************/ PtViewer::~PtViewer() { mGraphicsPPTBF->finalize(); delete mGraphicsPPTBF; mGraphicsPPTBF = nullptr; } /****************************************************************************** * Initialize Window ******************************************************************************/ void PtViewer::initializeWindow() { // Offscreen contexts // GLFW doesn't support creating contexts without an associated window. // However, contexts with hidden windows can be created with the GLFW_VISIBLE window hint. glfwWindowHint( GLFW_VISIBLE, GLFW_FALSE ); // uncomment these lines if on Apple OS X glfwWindowHint( GLFW_CONTEXT_VERSION_MAJOR, 4 ); glfwWindowHint( GLFW_CONTEXT_VERSION_MINOR, 6 ); glfwWindowHint( GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE ); // Ask for GL profile #if 1 glfwWindowHint( GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE ); mUseGLCoreProfile = true; #else glfwWindowHint( GLFW_OPENGL_PROFILE, GLFW_OPENGL_COMPAT_PROFILE ); mUseGLCoreProfile = false; #endif // Create window mWindow = glfwCreateWindow( 512, 512, "", nullptr, nullptr ); if ( ! mWindow ) { // Window or OpenGL context creation failed glfwTerminate(); exit( EXIT_FAILURE ); } // Need a GL context? glfwMakeContextCurrent( mWindow ); // User interface parameters // - Point process parameters uiPointProcess_tilingType = static_cast< int >( PtPPTBF::IRREGULAR ); uiPointProcess_jittering = 0.f; // - Window function parameters uiWindowFunction_windowShape = 2; uiWindowFunction_windowArity = 6.f; uiWindowFunction_windowLarp = 0.f; uiWindowFunction_windowNorm = 2.f; uiWindowFunction_windowSmooth = 0.f; uiWindowFunction_windowBlend = 1.0f; uiWindowFunction_windowSigwcell = 0.1f; uiWindowFunction_gaussianWindowDecay = 1.f; uiWindowFunction_gaussianWindowDecayVariation = 0.f; uiWindowFunction_gaussianWindowNorm = 2.f; // - Feature function parameters uiPPTBF_bombingFlag = 0; uiFeatureFunction_featureNorm = 2.f; uiFeatureFunction_winfeatcorrel = 0.f; uiFeatureFunction_anisotropy = 10.f; uiFeatureFunction_gaborMinNbKernels = 1; uiFeatureFunction_gaborMaxNbKernels = 2; uiFeatureFunction_gaborDecay = 1.f; uiFeatureFunction_gaborDecayVariation = 0.1f; uiFeatureFunction_gaborStripesFrequency = 0.f; uiFeatureFunction_featurePhaseShift = 0.f; uiFeatureFunction_gaborStripesThickness = 0.01f; uiFeatureFunction_gaborStripesCurvature = 0.f; uiFeatureFunction_gaborStripesOrientation = M_PI / 2.f; // - Deformations, Non-Stationarity and_Mixtures parameters uiDefNonStaAndMix_spatialDeformation = glm::vec3( 0.f, 0.f, 0.f ); uiDefNonStaAndMix_recursiveWindowSplittingProbability = 0.f; uiDefNonStaAndMix_recursiveWindowSplittingScaleRatio = 0.5f; // Global settings uiGlobalSettings_RESOL = 100; uiGlobalSettings_alpha = 0.f * M_PI; uiGlobalSettings_rescalex = 1.f; // PPTBF uiPPTBF_animation = false; uiPPTBF_megaKernel = true; uiPPTBF_timer = true; // Display binary visual structure mUIShowHistogram = true; // Debug uiGlobalSettings_useWindowFunction = true; uiGlobalSettings_useFeatureFunction = true; // Binary structure map uiBinaryStructureMap_nbBins = 10; uiBinaryStructureMap_threshold = 100; // Initialize window event handling // - custom user data glfwSetWindowUserPointer( mWindow, this ); // - window glfwSetWindowCloseCallback( mWindow, window_close_callback ); glfwSetWindowSizeCallback( mWindow, window_size_callback ); // - frame buffer glfwSetFramebufferSizeCallback( mWindow, framebuffer_size_callback ); } /****************************************************************************** * ... ******************************************************************************/ static void APIENTRY openglCallbackFunction( GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar* message, const void* userParam ) { /*(void)source; (void)type; (void)id; (void)severity; (void)length; (void)userParam; fprintf( stderr, "%s\n", message ); if ( severity == GL_DEBUG_SEVERITY_HIGH ) { fprintf( stderr, "Aborting...\n" ); abort(); }*/ // TEST if ( severity != GL_DEBUG_SEVERITY_HIGH ) //if ( severity != GL_DEBUG_SEVERITY_MEDIUM ) //if ( severity != GL_DEBUG_SEVERITY_LOW ) { return; } std::cout << "------------opengl-debug-callback------------" << std::endl; std::cout << "message: "<< message << std::endl; std::cout << "type: "; switch (type) { case GL_DEBUG_TYPE_ERROR: std::cout << "ERROR"; break; case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR: std::cout << "DEPRECATED_BEHAVIOR"; break; case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR: std::cout << "UNDEFINED_BEHAVIOR"; break; case GL_DEBUG_TYPE_PORTABILITY: std::cout << "PORTABILITY"; break; case GL_DEBUG_TYPE_PERFORMANCE: std::cout << "PERFORMANCE"; break; case GL_DEBUG_TYPE_OTHER: std::cout << "OTHER"; break; } std::cout << std::endl; std::cout << "id: " << id << std::endl; std::cout << "severity: "; switch (severity){ case GL_DEBUG_SEVERITY_LOW: std::cout << "LOW"; break; case GL_DEBUG_SEVERITY_MEDIUM: std::cout << "MEDIUM"; break; case GL_DEBUG_SEVERITY_HIGH: std::cout << "HIGH"; break; } std::cout << std::endl; } /****************************************************************************** * Initialize GL ******************************************************************************/ void PtViewer::initializeGL() { // Determine the OpenGL and GLSL versions mVendor = glGetString( GL_VENDOR ); mRenderer = glGetString( GL_RENDERER ); mVersion = glGetString( GL_VERSION ); mShadingLanguageVersion = glGetString( GL_SHADING_LANGUAGE_VERSION ); glGetIntegerv( GL_MAJOR_VERSION, &mMajorVersion ); glGetIntegerv( GL_MINOR_VERSION, &mMinorVersion ); // Determine the OpenGL and GLSL versions printf( "\n[Renderer Info]\n" ); printf( "\tGL Vendor: %s\n", mVendor ); printf( "\tGL Renderer: %s\n", mRenderer ); printf( "\tGL Version (string): %s\n", mVersion ); printf( "\tGL Version (integer): %d.%d\n", mMajorVersion, mMinorVersion ); printf( "\tGLSL Version: %s\n", mShadingLanguageVersion ); // Check for Bindless Texture extension if ( glfwExtensionSupported( "GL_ARB_bindless_texture" ) == GLFW_FALSE ) { std::cout << "\nERROR: GL_ARB_bindless_texture extension is not supported by the current context" << std::endl; exit( -1 ); } std::cout << "\n[Path configuration]" << std::endl; //std::string projectBinPath = ""; std::string projectPath = ""; std::string projectDataPath = ""; std::string projectImagePath = ""; std::string projectShaderPath = ""; //#ifdef PT_PROJECT_BIN_PATH // projectBinPath = "PT_PROJECT_BIN_PATH"; //#endif #ifdef PT_PROJECT_PATH projectPath = PT_PROJECT_PATH; #endif #ifdef PT_DATA_PATH projectDataPath = PtEnvironment::mDataPath; #endif #ifdef PT_IMAGE_PATH projectImagePath = PtEnvironment::mImagePath; #endif #ifdef PT_SHADER_PATH projectShaderPath = PtEnvironment::mShaderPath; #endif //printf( "PT_PROJECT_BIN_PATH: %s\n", projectBinPath.c_str() ); printf( "\tPROJECT\t%s\n", projectPath.c_str() ); printf( "\tDATA\t%s\n", projectDataPath.c_str() ); printf( "\tIMAGE\t%s\n", projectImagePath.c_str() ); printf( "\tSHADER\t%s\n", projectShaderPath.c_str() ); #if _DEBUG // Use a boolean in User Interface instead !!!!!!!!!!!!!!!!!!!!! // Enable graphics callback glEnable( GL_DEBUG_OUTPUT ); glEnable( GL_DEBUG_OUTPUT_SYNCHRONOUS ); glDebugMessageCallback( openglCallbackFunction, nullptr ); glDebugMessageControl( GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, NULL, true ); #endif // Initialize Graphics data int width, height; glfwGetWindowSize( mWindow, &width, &height ); //glfwGetFramebufferSize( mWindow, &width, &height ); glViewport( 0, 0, width, height ); // Initialize graphics PPTBF initializePPTBF( width, height ); // Initialize graphics PPTBF mGraphicsHistogram = new PtGraphicsHistogram(); mGraphicsHistogram->initialize( uiBinaryStructureMap_nbBins ); // Initialize timer(s) graphicsInitialization_Timer(); // Cannot draw with a bounded VAO in GL Core profile...? glGenVertexArrays( 1, &mGLCoreProfileVAO ); } /****************************************************************************** * ... ******************************************************************************/ void PtViewer::finalize() { // Cannot draw with a bounded VAO in GL Core profile...? glDeleteVertexArrays( 1, &mGLCoreProfileVAO ); // Finalize timer(s) graphicsFinalization_Timer(); glfwDestroyWindow( mWindow ); } /****************************************************************************** * Initialize PPTBF ******************************************************************************/ void PtViewer::initializePPTBF( const int pWidth, const int pHeight ) { // Update PPTBF mGraphicsPPTBF->setWidth( pWidth ); mGraphicsPPTBF->setHeight( pHeight ); // Initialize graphics PPTBF mGraphicsPPTBF->initialize( pWidth, pHeight ); // Upload PPTBF parameters to device (i.e. GPU) mGraphicsPPTBF->editPPTBFGeneratorShaderProgram()->use(); { // - general parameters mGraphicsPPTBF->setResolution( uiGlobalSettings_RESOL ); mGraphicsPPTBF->setAlpha( uiGlobalSettings_alpha * static_cast< float >( M_PI ) ); mGraphicsPPTBF->setRescalex( uiGlobalSettings_rescalex ); //mGraphicsPPTBF->setImageWidth( pWidth ); //mGraphicsPPTBF->setImageHeight( pHeight ); // - PPTBF mGraphicsPPTBF->setBombingFlag( uiPPTBF_bombingFlag ); // - point process mGraphicsPPTBF->setTilingType( uiPointProcess_tilingType ); mGraphicsPPTBF->setJittering( uiPointProcess_jittering ); mGraphicsPPTBF->setCellSubdivisionProbability( uiPointProcess_cellSubdivisionProbability ); mGraphicsPPTBF->setNbRelaxationIterations( uiPointProcess_nbRelaxationIterations ); // - window function mGraphicsPPTBF->setCellularToGaussianWindowBlend( uiWindowFunction_cellularVSGaussianWindowBlend ); mGraphicsPPTBF->setRectangularToVoronoiShapeBlend( uiWindowFunction_rectangularToVoronoiShapeBlend ); mGraphicsPPTBF->setCellularWindowNorm( uiWindowFunction_cellularWindowNorm ); mGraphicsPPTBF->setWindowShape( uiWindowFunction_windowShape ); mGraphicsPPTBF->setWindowArity( uiWindowFunction_windowArity ); mGraphicsPPTBF->setWindowLarp( uiWindowFunction_windowLarp ); mGraphicsPPTBF->setWindowNorm( uiWindowFunction_windowNorm ); mGraphicsPPTBF->setWindowSmooth( uiWindowFunction_windowSmooth ); mGraphicsPPTBF->setWindowBlend( uiWindowFunction_windowBlend ); mGraphicsPPTBF->setWindowSigwcell( uiWindowFunction_windowSigwcell ); mGraphicsPPTBF->setCellularWindowDecay( uiWindowFunction_cellularWindowDecay ); mGraphicsPPTBF->setGaussianWindowDecay( uiWindowFunction_gaussianWindowDecay ); mGraphicsPPTBF->setGaussianWindowDecayJittering( uiWindowFunction_gaussianWindowDecayVariation ); // - feature function mGraphicsPPTBF->setMinNbGaborKernels( uiFeatureFunction_gaborMinNbKernels ); mGraphicsPPTBF->setMaxNbGaborKernels( uiFeatureFunction_gaborMaxNbKernels ); mGraphicsPPTBF->setFeatureNorm( uiFeatureFunction_featureNorm ); mGraphicsPPTBF->setFeatureWinfeatcorrel( uiFeatureFunction_winfeatcorrel ); mGraphicsPPTBF->setFeatureAnisotropy( uiFeatureFunction_anisotropy ); mGraphicsPPTBF->setGaborStripesFrequency( static_cast< int >( uiFeatureFunction_gaborStripesFrequency ) ); mGraphicsPPTBF->setGaborStripesCurvature( uiFeatureFunction_gaborStripesCurvature ); mGraphicsPPTBF->setGaborStripesOrientation( uiFeatureFunction_gaborStripesOrientation ); mGraphicsPPTBF->setGaborStripesThickness( uiFeatureFunction_gaborStripesThickness ); mGraphicsPPTBF->setGaborDecay( uiFeatureFunction_gaborDecay ); mGraphicsPPTBF->setGaborDecayJittering( uiFeatureFunction_gaborDecayVariation ); mGraphicsPPTBF->setFeaturePhaseShift( uiFeatureFunction_featurePhaseShift * ( static_cast< float >( M_PI ) * 0.5f ) ); // - deformation mGraphicsPPTBF->setTurbulenceAmplitude0( uiDefNonStaAndMix_spatialDeformation.x ); mGraphicsPPTBF->setTurbulenceAmplitude1( uiDefNonStaAndMix_spatialDeformation.y ); mGraphicsPPTBF->setTurbulenceAmplitude2( uiDefNonStaAndMix_spatialDeformation.z ); // - recursivity mGraphicsPPTBF->setRecursiveWindowSubdivisionProbability( uiDefNonStaAndMix_recursiveWindowSplittingProbability ); mGraphicsPPTBF->setRecursiveWindowSubdivisionScale( uiDefNonStaAndMix_recursiveWindowSplittingScaleRatio ); // - animation mGraphicsPPTBF->setUseAnimation( uiPPTBF_animation ); } PtShaderProgram::unuse(); } /****************************************************************************** * ... ******************************************************************************/ GLFWwindow* PtViewer::getWindow() { return mWindow; } /****************************************************************************** * ... ******************************************************************************/ void PtViewer::window_close_callback( GLFWwindow* window ) { //printf("\nPtTextureSynthesizerViewer::window_close_callback"); //if ( ! time_to_close ) { glfwSetWindowShouldClose( window, GLFW_TRUE ); } //printf("window_close_callback"); } /****************************************************************************** * ... ******************************************************************************/ void PtViewer::window_size_callback( GLFWwindow* window, int width, int height ) { //printf( "window_size_callback = (%d,%d)", width, height ); } /****************************************************************************** * ... ******************************************************************************/ void PtViewer::framebuffer_size_callback( GLFWwindow* window, int width, int height ) { glViewport( 0, 0, width, height ); //printf( "framebuffer_size_callback = (%d,%d)", width, height ); static_cast< PtViewer* >( glfwGetWindowUserPointer( window ) )->onSizeModified( width, height ); } /****************************************************************************** * Callback called when PPTBF size has been modified ******************************************************************************/ void PtViewer::onSizeModified( const int pWidth, const int pHeight ) { // Update PPTBF //mGraphicsPPTBF->setWidth( pWidth ); //mGraphicsPPTBF->setHeight( pHeight ); mGraphicsPPTBF->setImageWidth( pWidth ); mGraphicsPPTBF->setImageHeight( pHeight ); //mGraphicsPPTBF->editPPTBFGeneratorShaderProgram()->use(); //mGraphicsPPTBF->setImageWidth( pWidth ); //mGraphicsPPTBF->setImageHeight( pHeight ); //PtShaderProgram::unuse(); mPPTBFUpdateRequested = true; // Update PPTBF framebuffer mGraphicsPPTBF->onSizeModified( pWidth, pHeight ); } /****************************************************************************** * Refresh ******************************************************************************/ void PtViewer::refresh() { // Set context // NOTE: // By default, making a context non-current implicitly forces a pipeline flush // On machines that support GL_KHR_context_flush_control, you can control whether a context performs this flush by setting the GLFW_CONTEXT_RELEASE_BEHAVIOR window hint. glfwMakeContextCurrent( getWindow() ); // Render scene //render(); // Swap buffers glfwSwapBuffers( getWindow() ); } /****************************************************************************** * Initialize timer(s) ******************************************************************************/ void PtViewer::graphicsInitialization_Timer() { // Device timer glCreateQueries( GL_TIME_ELAPSED, 1, &mQueryTimeElapsed ); } /****************************************************************************** * Finalize timer(s) ******************************************************************************/ void PtViewer::graphicsFinalization_Timer() { // Device timer glDeleteQueries( 1, &mQueryTimeElapsed ); } /****************************************************************************** * ... ******************************************************************************/ void PtViewer::synthesize() { } /****************************************************************************** * Slot called when the data model has been modified ******************************************************************************/ void PtViewer::onDataModelModified() { } /****************************************************************************** * Handle requests ******************************************************************************/ void PtViewer::handleRequests() { // handle Requests stage //std::cout << "\nHandle requests..." << std::endl; // Generate PPTBF // - check if PPTBF computation is requested (Update UI edition flag) if ( mPPTBFUpdateRequested ) { mPPTBFUpdateRequested = false; // TEST // Compute PPTBF //mGraphicsPPTBF->setTime( static_cast< float >( glfwGetTime() ) ); // TODO: no active program !!!!!!!!!! //mGraphicsPPTBF->compute(); // Update UI edition flag //mPPTBFUpdateRequested = false; } } /****************************************************************************** * Get synthesizer ******************************************************************************/ PtGraphicsPPTBF* PtViewer::getPPTBF() { return mGraphicsPPTBF; }
20,416
C++
.cpp
508
37.88189
170
0.594985
ASTex-ICube/semiproctex
39
8
2
LGPL-2.1
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,913
PtApplication.cpp
ASTex-ICube_semiproctex/PPTBF_Structures_Src/Tools/PtViewer/PtApplication.cpp
/* * Publication: Semi-Procedural Textures Using Point Process Texture Basis Functions * Authors: anonymous * * Code author: Pascal Guehl * * anonymous * anonymous */ /** * @version 1.0 */ #include "PtApplication.h" /****************************************************************************** ******************************* INCLUDE SECTION ****************************** ******************************************************************************/ #if _WIN32 #define NOMINMAX #include <windows.h> #endif // STL #include <iostream> // Project #include "PtPPTBF.h" #include "PtViewer.h" #include <PtModelLibrary.h> #include <PtGraphicsLibrary.h> // ImGui #include <imgui.h> #include "imgui_impl_glfw_gl3.h" /****************************************************************************** ****************************** NAMESPACE SECTION ***************************** ******************************************************************************/ // Project using namespace Pt; using namespace PtGraphics; using namespace PtGUI; // STL using namespace std; /****************************************************************************** ************************* DEFINE AND CONSTANT SECTION ************************ ******************************************************************************/ /** * The unique instance of the singleton. */ PtApplication* PtApplication::msInstance = nullptr; /****************************************************************************** ***************************** TYPE DEFINITION ******************************** ******************************************************************************/ /****************************************************************************** ***************************** METHOD DEFINITION ****************************** ******************************************************************************/ /****************************************************************************** * Get the unique instance. * * @return the unique instance ******************************************************************************/ PtApplication& PtApplication::get() { if ( msInstance == nullptr ) { msInstance = new PtApplication(); } return *msInstance; } /****************************************************************************** * Default constructor ******************************************************************************/ PtApplication::PtApplication() : mMainWindow( nullptr ) { // User interface mMainWindow = new PtViewer(); } /****************************************************************************** * Destructor ******************************************************************************/ PtApplication::~PtApplication() { // User interface delete mMainWindow; } /****************************************************************************** * Initialize ******************************************************************************/ bool PtApplication::initialize( const char* const pWorkingDirectory ) { bool statusOK = false; statusOK = Pt::PtDataModelLibrary::initialize( pWorkingDirectory ); if ( ! statusOK ) { return false; } statusOK = PtGraphics::PtGraphicsLibrary::initialize( pWorkingDirectory ); if ( ! statusOK ) { return false; } // Initialize the GLFW library initializeGLFW(); // Initialize windows // - at least, create one graphics context initializeWindows(); // Initialize GL library initializeGL(); // Initialize user interface //initializeImGuiUserInterface(); // already done in MainWindow... return true; } /****************************************************************************** * Finalize ******************************************************************************/ void PtApplication::finalize() { // Finalize the GLFW library finalizeGLFW(); } /****************************************************************************** * Initialize GLFW ******************************************************************************/ void PtApplication::initializeGLFW() { // Initialize GLFW library if ( ! glfwInit() ) { // Initialization failed exit( EXIT_FAILURE ); } // Set error callback glfwSetErrorCallback( error_callback ); } /****************************************************************************** * Finalize GLFW ******************************************************************************/ void PtApplication::finalizeGLFW() { glfwTerminate(); } /****************************************************************************** * GLFW error callback ******************************************************************************/ void PtApplication::error_callback( int error, const char* description ) { fprintf( stderr, "Error: %s\n", description ); } /****************************************************************************** * Initialize windows ******************************************************************************/ void PtApplication::initializeWindows() { // Initialize windows mMainWindow->initializeWindow(); } /****************************************************************************** * Initialize GL library ******************************************************************************/ void PtApplication::initializeGL() { // NOTE: the following GLFW functions require a context to be current glfwMakeContextCurrent( mMainWindow->getWindow() ); // Load OpenGL API/extensions gladLoadGLLoader( (GLADloadproc)glfwGetProcAddress ); // Managing swap interval //glfwSwapInterval( 1 ); glfwSwapInterval( 0 ); // Initialize mMainWindow->initializeGL(); } /****************************************************************************** * Initialize ImGui user interface ******************************************************************************/ void PtApplication::initializeImGuiUserInterface() { // Need a GL context? glfwMakeContextCurrent( mMainWindow->getWindow() ); // Initialize ImGui // - GL binding ImGui_ImplGlfwGL3_Init( mMainWindow->getWindow(), true ); // TODO: check callback: erased/overlapped by ImGui: use custom and call ImGui one !!! () => use FALSE !!!! // - style ImGui::StyleColorsClassic(); //ImGui::StyleColorsDark(); } /****************************************************************************** * Execute * - main event loop ******************************************************************************/ void PtApplication::execute() { while ( ! glfwWindowShouldClose( mMainWindow->getWindow() ) ) { // Set context // NOTE: // By default, making a context non-current implicitly forces a pipeline flush // On machines that support GL_KHR_context_flush_control, you can control whether a context performs this flush by setting the GLFW_CONTEXT_RELEASE_BEHAVIOR window hint. glfwMakeContextCurrent( mMainWindow->getWindow() ); // Render scene mMainWindow->refresh(); // Handle requests // - data model loading, descriptors computation, texture synthesis, painting, etc... handleRequests(); // Process events glfwPollEvents(); } } /****************************************************************************** * Handle requests ******************************************************************************/ void PtApplication::handleRequests() { mMainWindow->handleRequests(); } /****************************************************************************** * Post a request ******************************************************************************/ void PtApplication::postRequest( PtPipelineRequest pRequest ) { switch ( pRequest ) { case eLoadDataModel: mOmniScaleModelUpdateRequested = true; break; case eSynthesizeTexture: mTextureSynthesisRequested = true; break; default: break; } }
7,835
C++
.cpp
228
32.324561
171
0.425321
ASTex-ICube/semiproctex
39
8
2
LGPL-2.1
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,914
main.cpp
ASTex-ICube_semiproctex/PPTBF_Structures_Src/Tools/PtViewer/main.cpp
/* * Publication: Semi-Procedural Textures Using Point Process Texture Basis Functions * Authors: anonymous * * Code author: Pascal Guehl * * anonymous * anonymous */ /** * @version 1.0 */ /****************************************************************************** ******************************* INCLUDE SECTION ****************************** ******************************************************************************/ // STL #include <iostream> #include <string> // System #include <cstdlib> #include <ctime> // Project #include "PtApplication.h" #include <PtEnvironment.h> #include <string> #include <fstream> #include <iostream> #include <vector> #include <sstream> /****************************************************************************** ****************************** NAMESPACE SECTION ***************************** ******************************************************************************/ /****************************************************************************** ************************* DEFINE AND CONSTANT SECTION ************************ ******************************************************************************/ /****************************************************************************** ***************************** TYPE DEFINITION ******************************** ******************************************************************************/ /****************************************************************************** ***************************** METHOD DEFINITION ****************************** ******************************************************************************/ /****************************************************************************** * Main entry program * * @param pArgc Number of arguments * @param pArgv List of arguments * * @return flag telling whether or not it succeeds ******************************************************************************/ int main( int pArgc, char** pArgv ) { std::cout << "------------------------" << std::endl; std::cout << "- PPTBF Designer Tool --" << std::endl; std::cout << "------------------------" << std::endl; // Retrieve program directory int indexParameter = 0; std::string workingDirectory = ""; workingDirectory = pArgv[ indexParameter++ ]; PtGUI::PtApplication::get(); PtGUI::PtApplication::get().initialize( workingDirectory.c_str() ); // Special settings // - check command line arguments const int nbArguments = 1; if ( pArgc >= ( 1 + nbArguments ) ) { Pt::PtEnvironment::mImagePath = std::string( pArgv[ indexParameter++ ] ); } PtGUI::PtApplication::get().execute(); PtGUI::PtApplication::get().finalize(); // todo: add a GLOBAL static finalize(); return 0; }
2,763
C++
.cpp
72
36.444444
84
0.369622
ASTex-ICube/semiproctex
39
8
2
LGPL-2.1
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,915
PtViewer.cpp
ASTex-ICube_semiproctex/PPTBF_Structures_Src/Tools/PtViewer/PtViewer.cpp
/* * Publication: Semi-Procedural Textures Using Point Process Texture Basis Functions * Authors: anonymous * * Code author: Pascal Guehl * * anonymous * anonymous */ /** * @version 1.0 */ #include "PtViewer.h" /****************************************************************************** ******************************* INCLUDE SECTION ****************************** ******************************************************************************/ #if _WIN32 #define NOMINMAX #include <windows.h> #endif // GL #include <glad/glad.h> // STL #include <string> #include <iostream> #include <fstream> #include <algorithm> #include <functional> #include <numeric> #include <iomanip> #include <algorithm> // glm //#include <glm/gtc/type_ptr.hpp> // ImGui #define IMGUI_DEFINE_MATH_OPERATORS // => Anonymous #include <imgui.h> #include "imgui_impl_glfw_gl3.h" #include <imgui_internal.h> // Project #include "PtApplication.h" #include "PtShaderProgram.h" #include "PtPPTBFLoader.h" #include "PtGraphicsPPTBF.h" #include "PtGraphicsHistogram.h" #include "PtGraphicsMeshManager.h" #include "PtCamera.h" #include "PtImageHelper.h" #include <PtEnvironment.h> /****************************************************************************** ****************************** NAMESPACE SECTION ***************************** ******************************************************************************/ // Project using namespace Pt; using namespace PtGraphics; using namespace PtGUI; /****************************************************************************** ************************* DEFINE AND CONSTANT SECTION ************************ ******************************************************************************/ /****************************************************************************** ***************************** TYPE DEFINITION ******************************** ******************************************************************************/ /****************************************************************************** ***************************** METHOD DEFINITION ****************************** ******************************************************************************/ /****************************************************************************** ***************************** METHOD DEFINITION ****************************** ******************************************************************************/ /****************************************************************************** * Default constructor ******************************************************************************/ PtViewer::PtViewer() : mWindow( nullptr ) , mCamera( nullptr ) , mLaunchRequest( false ) , mShowUI( true ) , mGraphicsPPTBF( nullptr ) , mGraphicsHistogram( nullptr ) , mPPTBFUpdateRequested( true ) , mHistogramUpdateRequested( false ) , mUIShowHistogram( false ) , mBinaryStructureMapThreshold( 0.f ) , mUseRealTime( false ) , mUseGLCoreProfile( false ) , mGLCoreProfileVAO( 0 ) , mGraphicsMeshManager( nullptr ) { uiModelFilename = std::string(); uiTextureSynthesis_launch = false; // PPTBF mGraphicsPPTBF = new PtGraphicsPPTBF(); mGraphicsMeshManager = new PtGraphicsMeshManager(); // Initialize camera mCamera = new PtCamera(); mCamera->setCameraType( PtCamera::ePerspective ); mCamera->setEye( glm::vec3( 0.f, 0.f, 5.f ) ); } /****************************************************************************** * Destructor ******************************************************************************/ PtViewer::~PtViewer() { delete mCamera; mCamera = nullptr; mGraphicsMeshManager->finalize(); delete mGraphicsMeshManager; mGraphicsMeshManager = nullptr; mGraphicsPPTBF->finalize(); delete mGraphicsPPTBF; mGraphicsPPTBF = nullptr; } /****************************************************************************** * Initialize Window ******************************************************************************/ void PtViewer::initializeWindow() { // uncomment these lines if on Apple OS X glfwWindowHint( GLFW_CONTEXT_VERSION_MAJOR, 4 ); glfwWindowHint( GLFW_CONTEXT_VERSION_MINOR, 6 ); glfwWindowHint( GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE ); // Ask for GL profile #if 1 glfwWindowHint( GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE ); mUseGLCoreProfile = true; #else glfwWindowHint( GLFW_OPENGL_PROFILE, GLFW_OPENGL_COMPAT_PROFILE ); mUseGLCoreProfile = false; #endif // Create window #if 0 mWindow = glfwCreateWindow( 1280, 720, "PPTBF Designer", nullptr, nullptr ); #else mWindow = glfwCreateWindow( 512, 512, "PPTBF Designer", nullptr, nullptr ); #endif if ( ! mWindow ) { // Window or OpenGL context creation failed glfwTerminate(); exit( EXIT_FAILURE ); } // Initialize ImGui // Need a GL context? glfwMakeContextCurrent( mWindow ); // - GL binding const bool install_callbacks = false; // customize call: call ImGui ones then custom ones ImGui_ImplGlfwGL3_Init( mWindow, install_callbacks ); // - style ImGui::StyleColorsClassic(); //ImGui::StyleColorsDark(); // User interface parameters // - Point process parameters uiPointProcess_tilingType = static_cast< int >( PtPPTBF::IRREGULAR ); uiPointProcess_jittering = 0.f; // - Window function parameters uiWindowFunction_windowShape = 2; uiWindowFunction_windowArity = 2.f; uiWindowFunction_windowLarp = 0.f; uiWindowFunction_windowNorm = 2.f; uiWindowFunction_windowSmooth = 0.f; uiWindowFunction_windowBlend = 1.0f; uiWindowFunction_windowSigwcell = 0.1f; uiWindowFunction_gaussianWindowDecay = 1.f; uiWindowFunction_gaussianWindowDecayVariation = 0.f; uiWindowFunction_gaussianWindowNorm = 2.f; // - Feature function parameters uiPPTBF_bombingFlag = 0; uiFeatureFunction_featureNorm = 2.f; uiFeatureFunction_winfeatcorrel = 0.f; uiFeatureFunction_anisotropy = 0.f; uiFeatureFunction_gaborMinNbKernels = 1; uiFeatureFunction_gaborMaxNbKernels = 2; uiFeatureFunction_gaborDecay = 1.f; uiFeatureFunction_gaborDecayVariation = 0.1f; uiFeatureFunction_gaborStripesFrequency = 0.f; uiFeatureFunction_featurePhaseShift = 0.f; uiFeatureFunction_gaborStripesThickness = 0.01f; uiFeatureFunction_gaborStripesCurvature = 0.f; uiFeatureFunction_gaborStripesOrientation = static_cast< float >( M_PI ) / 2.f; // - Deformations, Non-Stationarity and_Mixtures parameters uiDefNonStaAndMix_spatialDeformation = glm::vec3( 0.f, 0.f, 0.f ); uiDefNonStaAndMix_recursiveWindowSplittingProbability = 0.f; uiDefNonStaAndMix_recursiveWindowSplittingScaleRatio = 0.5f; // Global settings uiGlobalSettings_RESOL = 100; uiGlobalSettings_alpha = 0.f * M_PI; uiGlobalSettings_rescalex = 1.f; // PPTBF uiPPTBF_animation = false; uiPPTBF_megaKernel = true; uiPPTBF_timer = true; // Display binary visual structure mUIShowHistogram = true; // Debug uiGlobalSettings_useWindowFunction = true; uiGlobalSettings_useFeatureFunction = true; // Binary structure map uiBinaryStructureMap_nbBins = 128; uiBinaryStructureMap_threshold = 75; // Initialize window event handling // - custom user data glfwSetWindowUserPointer( mWindow, this ); // - window glfwSetWindowCloseCallback( mWindow, window_close_callback ); glfwSetWindowSizeCallback( mWindow, window_size_callback ); glfwSetWindowPosCallback( mWindow, window_pos_callback ); // - frame buffer glfwSetFramebufferSizeCallback( mWindow, framebuffer_size_callback ); // - mouse glfwSetCursorPosCallback( mWindow, cursor_position_callback ); glfwSetMouseButtonCallback( mWindow, mouse_button_callback ); glfwSetScrollCallback( mWindow, scroll_callback ); // - keyboard glfwSetKeyCallback( mWindow, key_callback ); // - text input glfwSetCharCallback( mWindow, character_callback ); } /****************************************************************************** * ... ******************************************************************************/ static void APIENTRY openglCallbackFunction( GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar* message, const void* userParam ) { /*(void)source; (void)type; (void)id; (void)severity; (void)length; (void)userParam; fprintf( stderr, "%s\n", message ); if ( severity == GL_DEBUG_SEVERITY_HIGH ) { fprintf( stderr, "Aborting...\n" ); abort(); }*/ // TEST if ( severity != GL_DEBUG_SEVERITY_HIGH ) //if ( severity != GL_DEBUG_SEVERITY_MEDIUM ) //if ( severity != GL_DEBUG_SEVERITY_LOW ) { return; } std::cout << "------------opengl-debug-callback------------" << std::endl; std::cout << "message: "<< message << std::endl; std::cout << "type: "; switch (type) { case GL_DEBUG_TYPE_ERROR: std::cout << "ERROR"; break; case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR: std::cout << "DEPRECATED_BEHAVIOR"; break; case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR: std::cout << "UNDEFINED_BEHAVIOR"; break; case GL_DEBUG_TYPE_PORTABILITY: std::cout << "PORTABILITY"; break; case GL_DEBUG_TYPE_PERFORMANCE: std::cout << "PERFORMANCE"; break; case GL_DEBUG_TYPE_OTHER: std::cout << "OTHER"; break; } std::cout << std::endl; std::cout << "id: " << id << std::endl; std::cout << "severity: "; switch (severity){ case GL_DEBUG_SEVERITY_LOW: std::cout << "LOW"; break; case GL_DEBUG_SEVERITY_MEDIUM: std::cout << "MEDIUM"; break; case GL_DEBUG_SEVERITY_HIGH: std::cout << "HIGH"; break; } std::cout << std::endl; } /****************************************************************************** * Initialize GL ******************************************************************************/ void PtViewer::initializeGL() { // Determine the OpenGL and GLSL versions mVendor = glGetString( GL_VENDOR ); mRenderer = glGetString( GL_RENDERER ); mVersion = glGetString( GL_VERSION ); mShadingLanguageVersion = glGetString( GL_SHADING_LANGUAGE_VERSION ); glGetIntegerv( GL_MAJOR_VERSION, &mMajorVersion ); glGetIntegerv( GL_MINOR_VERSION, &mMinorVersion ); // Determine the OpenGL and GLSL versions printf( "\n[Renderer Info]\n" ); printf( "\tGL Vendor: %s\n", mVendor ); printf( "\tGL Renderer: %s\n", mRenderer ); printf( "\tGL Version (string): %s\n", mVersion ); printf( "\tGL Version (integer): %d.%d\n", mMajorVersion, mMinorVersion ); printf( "\tGLSL Version: %s\n", mShadingLanguageVersion ); // Check for Bindless Texture extension if ( glfwExtensionSupported( "GL_ARB_bindless_texture" ) == GLFW_FALSE ) { std::cout << "\nERROR: GL_ARB_bindless_texture extension is not supported by the current context" << std::endl; exit( -1 ); } std::cout << "\n[Path configuration]" << std::endl; //std::string projectBinPath = ""; std::string projectPath = ""; std::string projectDataPath = ""; std::string projectImagePath = ""; std::string projectShaderPath = ""; //#ifdef PT_PROJECT_BIN_PATH // projectBinPath = "PT_PROJECT_BIN_PATH"; //#endif #ifdef PT_PROJECT_PATH projectPath = PT_PROJECT_PATH; #endif #ifdef PT_DATA_PATH projectDataPath = PtEnvironment::mDataPath; #endif #ifdef PT_IMAGE_PATH projectImagePath = PtEnvironment::mImagePath; #endif #ifdef PT_SHADER_PATH projectShaderPath = PtEnvironment::mShaderPath; #endif //printf( "PT_PROJECT_BIN_PATH: %s\n", projectBinPath.c_str() ); printf( "\tPROJECT\t%s\n", projectPath.c_str() ); printf( "\tDATA\t%s\n", projectDataPath.c_str() ); printf( "\tIMAGE\t%s\n", projectImagePath.c_str() ); printf( "\tSHADER\t%s\n", projectShaderPath.c_str() ); #if _DEBUG // Use a boolean in User Interface instead !!!!!!!!!!!!!!!!!!!!! // Enable graphics callback glEnable( GL_DEBUG_OUTPUT ); glEnable( GL_DEBUG_OUTPUT_SYNCHRONOUS ); glDebugMessageCallback( openglCallbackFunction, nullptr ); glDebugMessageControl( GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, NULL, true ); #endif // Initialize Graphics data int width, height; glfwGetWindowSize( mWindow, &width, &height ); //glfwGetFramebufferSize( mWindow, &width, &height ); glViewport( 0, 0, width, height ); // Initialize graphics PPTBF initializePPTBF( width, height ); // Initialize graphics PPTBF mGraphicsHistogram = new PtGraphicsHistogram(); mGraphicsHistogram->initialize( uiBinaryStructureMap_nbBins ); uiBinaryStructureMap_threshold = 75; // - resize containers on Host const int nbBins = mGraphicsHistogram->getNbBins(); histogram.resize( nbBins, 0.f ); CDF.resize( nbBins, 0.f ); // Initialize timer(s) graphicsInitialization_Timer(); // Cannot draw with a bounded VAO in GL Core profile...? glGenVertexArrays( 1, &mGLCoreProfileVAO ); // Initialize mesh manager mGraphicsMeshManager->initialize(); mGraphicsMeshManager->setPPTBFTexture( mGraphicsPPTBF->mPPTBFTexture ); // Generate a grid mesh mGraphicsMeshManager->setMeshType( PtGraphicsMeshManager::MeshType::eTorusMesh ); mGraphicsMeshManager->setUseMaterial( true ); //---------------------------------------------------- GLuint& texture = mTransferFunctionTex; glCreateTextures( GL_TEXTURE_2D, 1, &texture ); // - set texture wrapping/filtering options // Common GL parameters const GLint param_TEXTURE_WRAP_S = GL_CLAMP_TO_EDGE; /*GL_REPEAT*/ const GLint param_TEXTURE_WRAP_T = GL_CLAMP_TO_EDGE; /*GL_REPEAT*/ const GLint param_TEXTURE_MIN_FILTER = GL_NEAREST; /*GL_LINEAR*/ const GLint param_TEXTURE_MAG_FILTER = GL_NEAREST; /*GL_LINEAR*/ glTextureParameteri( texture, GL_TEXTURE_WRAP_S, param_TEXTURE_WRAP_S ); glTextureParameteri( texture, GL_TEXTURE_WRAP_T, param_TEXTURE_WRAP_T ); glTextureParameteri( texture, GL_TEXTURE_MIN_FILTER, param_TEXTURE_MIN_FILTER ); glTextureParameteri( texture, GL_TEXTURE_MAG_FILTER, param_TEXTURE_MAG_FILTER ); // - set min/max level for completeness glTextureParameteri( texture, GL_TEXTURE_BASE_LEVEL, 0 ); glTextureParameteri( texture, GL_TEXTURE_MAX_LEVEL, 0 ); // - allocate memory glTextureStorage2D( texture, 1/*levels*/, GL_RGBA32F, 256/*width*/, 1/*height*/ ); // - clear texture glm::vec4 nullData = glm::vec4( 0.f ); glClearTexImage( texture, 0/*level*/, GL_RGBA, GL_FLOAT, glm::value_ptr( nullData ) ); } /****************************************************************************** * ... ******************************************************************************/ void PtViewer::finalize() { // Cannot draw with a bounded VAO in GL Core profile...? glDeleteVertexArrays( 1, &mGLCoreProfileVAO ); // Finalize timer(s) graphicsFinalization_Timer(); // Finalize ImGui ImGui_ImplGlfwGL3_Shutdown(); glfwDestroyWindow( mWindow ); } /****************************************************************************** * Initialize PPTBF ******************************************************************************/ void PtViewer::initializePPTBF( const int pWidth, const int pHeight ) { // Update PPTBF mGraphicsPPTBF->setWidth( pWidth ); mGraphicsPPTBF->setHeight( pHeight ); // Initialize graphics PPTBF mGraphicsPPTBF->initialize( pWidth, pHeight ); // Upload PPTBF parameters to device (i.e. GPU) mGraphicsPPTBF->editPPTBFGeneratorShaderProgram()->use(); { // - general parameters mGraphicsPPTBF->setResolution( uiGlobalSettings_RESOL ); mGraphicsPPTBF->setAlpha( uiGlobalSettings_alpha * static_cast< float >( M_PI ) ); mGraphicsPPTBF->setRescalex( uiGlobalSettings_rescalex ); //mGraphicsPPTBF->setImageWidth( pWidth ); //mGraphicsPPTBF->setImageHeight( pHeight ); // - PPTBF mGraphicsPPTBF->setBombingFlag( uiPPTBF_bombingFlag ); // - point process mGraphicsPPTBF->setTilingType( uiPointProcess_tilingType ); mGraphicsPPTBF->setJittering( uiPointProcess_jittering ); mGraphicsPPTBF->setCellSubdivisionProbability( uiPointProcess_cellSubdivisionProbability ); mGraphicsPPTBF->setNbRelaxationIterations( uiPointProcess_nbRelaxationIterations ); // - window function mGraphicsPPTBF->setCellularToGaussianWindowBlend( uiWindowFunction_cellularVSGaussianWindowBlend ); mGraphicsPPTBF->setRectangularToVoronoiShapeBlend( uiWindowFunction_rectangularToVoronoiShapeBlend ); mGraphicsPPTBF->setCellularWindowNorm( uiWindowFunction_cellularWindowNorm ); mGraphicsPPTBF->setWindowShape( uiWindowFunction_windowShape ); mGraphicsPPTBF->setWindowArity( uiWindowFunction_windowArity ); mGraphicsPPTBF->setWindowLarp( uiWindowFunction_windowLarp ); mGraphicsPPTBF->setWindowNorm( uiWindowFunction_windowNorm ); mGraphicsPPTBF->setWindowSmooth( uiWindowFunction_windowSmooth ); mGraphicsPPTBF->setWindowBlend( uiWindowFunction_windowBlend ); mGraphicsPPTBF->setWindowSigwcell( uiWindowFunction_windowSigwcell ); mGraphicsPPTBF->setCellularWindowDecay( uiWindowFunction_cellularWindowDecay ); mGraphicsPPTBF->setGaussianWindowDecay( uiWindowFunction_gaussianWindowDecay ); mGraphicsPPTBF->setGaussianWindowDecayJittering( uiWindowFunction_gaussianWindowDecayVariation ); // - feature function mGraphicsPPTBF->setMinNbGaborKernels( uiFeatureFunction_gaborMinNbKernels ); mGraphicsPPTBF->setMaxNbGaborKernels( uiFeatureFunction_gaborMaxNbKernels ); mGraphicsPPTBF->setFeatureNorm( uiFeatureFunction_featureNorm ); mGraphicsPPTBF->setFeatureWinfeatcorrel( uiFeatureFunction_winfeatcorrel ); mGraphicsPPTBF->setFeatureAnisotropy( uiFeatureFunction_anisotropy ); mGraphicsPPTBF->setGaborStripesFrequency( static_cast< int >( uiFeatureFunction_gaborStripesFrequency ) ); mGraphicsPPTBF->setGaborStripesCurvature( uiFeatureFunction_gaborStripesCurvature ); mGraphicsPPTBF->setGaborStripesOrientation( uiFeatureFunction_gaborStripesOrientation ); mGraphicsPPTBF->setGaborStripesThickness( uiFeatureFunction_gaborStripesThickness ); mGraphicsPPTBF->setGaborDecay( uiFeatureFunction_gaborDecay ); mGraphicsPPTBF->setGaborDecayJittering( uiFeatureFunction_gaborDecayVariation ); mGraphicsPPTBF->setFeaturePhaseShift( uiFeatureFunction_featurePhaseShift * ( static_cast< float >( M_PI ) * 0.5f ) ); // - deformation mGraphicsPPTBF->setTurbulenceAmplitude0( uiDefNonStaAndMix_spatialDeformation.x ); mGraphicsPPTBF->setTurbulenceAmplitude1( uiDefNonStaAndMix_spatialDeformation.y ); mGraphicsPPTBF->setTurbulenceAmplitude2( uiDefNonStaAndMix_spatialDeformation.z ); // - recursivity mGraphicsPPTBF->setRecursiveWindowSubdivisionProbability( uiDefNonStaAndMix_recursiveWindowSplittingProbability ); mGraphicsPPTBF->setRecursiveWindowSubdivisionScale( uiDefNonStaAndMix_recursiveWindowSplittingScaleRatio ); // - animation mGraphicsPPTBF->setUseAnimation( uiPPTBF_animation ); } PtShaderProgram::unuse(); bool statusOK = false; // Global variables const std::string shaderPath = PtEnvironment::mShaderPath + std::string( "/" ); PtShaderProgram* shaderProgram = nullptr; PtShaderProgram::TShaderList shaders; std::string shaderFilename; std::vector< std::string > uniforms; } /****************************************************************************** * ... ******************************************************************************/ GLFWwindow* PtViewer::getWindow() { return mWindow; } /****************************************************************************** * ... ******************************************************************************/ void PtViewer::key_callback( GLFWwindow* window, int key, int scancode, int action, int mods ) { // Call ImGui callback ImGui_ImplGlfwGL3_KeyCallback( window, key, scancode, action, mods ); //printf( "\nPtTextureSynthesizerViewer::key_callback" ); /*if ( static_cast< PtViewer* >(glfwGetWindowUserPointer(window)) != this ) { return; }*/ if ( key == GLFW_KEY_ESCAPE && action == GLFW_PRESS ) { glfwSetWindowShouldClose( window, GLFW_TRUE ); } if ( key == GLFW_KEY_SPACE && action == GLFW_RELEASE ) { const bool currentFlag = static_cast< PtViewer* >( glfwGetWindowUserPointer( window ) )->mShowUI; static_cast< PtViewer* >( glfwGetWindowUserPointer( window ) )->mShowUI = ( ! currentFlag ); } // printf("key_callback = (%d,%d,%d,%d)", key, scancode, action, mods); } /****************************************************************************** * ... ******************************************************************************/ void PtViewer::character_callback( GLFWwindow* window, unsigned int codepoint ) { // Call ImGui callback ImGui_ImplGlfwGL3_CharCallback( window, codepoint ); // Call Pt callback static_cast< PtViewer* >( glfwGetWindowUserPointer( window ) )->processCharacterEvent( codepoint ); } /****************************************************************************** * ... ******************************************************************************/ void PtViewer::processCharacterEvent( unsigned int codepoint ) { const int keyStatus = glfwGetKey( mWindow, GLFW_KEY_R ); if ( keyStatus == GLFW_PRESS ) { mGraphicsMeshManager->mModelMatrix = glm::mat4( 1.f ); mCamera->setEye( glm::vec3( 0.f, 0.f, 5.f ) ); } } /****************************************************************************** * ... ******************************************************************************/ void PtViewer::window_close_callback( GLFWwindow* window ) { //printf("\nPtTextureSynthesizerViewer::window_close_callback"); //if ( ! time_to_close ) { glfwSetWindowShouldClose( window, GLFW_TRUE ); } //printf("window_close_callback"); } /****************************************************************************** * ... ******************************************************************************/ void PtViewer::window_size_callback( GLFWwindow* window, int width, int height ) { //printf( "window_size_callback = (%d,%d)", width, height ); } /****************************************************************************** * ... ******************************************************************************/ void PtViewer::framebuffer_size_callback( GLFWwindow* window, int width, int height ) { glViewport( 0, 0, width, height ); static_cast< PtViewer* >( glfwGetWindowUserPointer( window ) )->onSizeModified( width, height ); } /****************************************************************************** * Callback called when PPTBF size has been modified ******************************************************************************/ void PtViewer::onSizeModified( const int pWidth, const int pHeight ) { const float aspect = static_cast< float >( pWidth ) / static_cast< float >( pHeight ); mCamera->setAspect( aspect ); } /****************************************************************************** * ... ******************************************************************************/ void PtViewer::window_pos_callback( GLFWwindow* window, int xpos, int ypos ) { // printf( "window_pos_callback = (%d,%d)", xpos, ypos ); } /****************************************************************************** * ... ******************************************************************************/ void PtViewer::cursor_position_callback( GLFWwindow* window, double xpos, double ypos ) { //printf( "\ncursor_position_callback = (%f,%f)", xpos, ypos ); static_cast< PtViewer* >( glfwGetWindowUserPointer( window ) )->processMouseMoveEvent( xpos, ypos ); } /****************************************************************************** * ... ******************************************************************************/ void PtViewer::processMouseMoveEvent( double xpos, double ypos ) { static double lastPosX = xpos; static double lastPosY = ypos; const int mouseButtonLeftStatus = glfwGetMouseButton( mWindow, GLFW_MOUSE_BUTTON_LEFT ); const int mouseButtonRightStatus = glfwGetMouseButton( mWindow, GLFW_MOUSE_BUTTON_RIGHT ); const int keyStatus = glfwGetKey( mWindow, GLFW_KEY_LEFT_CONTROL ); const int keyAltStatus = glfwGetKey( mWindow, GLFW_KEY_LEFT_ALT ); const int keyShiftStatus = glfwGetKey( mWindow, GLFW_KEY_LEFT_SHIFT ); // Handle rotation movements if ( mouseButtonLeftStatus == GLFW_PRESS && keyStatus == GLFW_PRESS ) { //mCamera->truck( 0.01f * ( xpos - lastPosX ) ); const float xoffset = static_cast< float >( xpos - lastPosX ); const float yoffset = static_cast< float >( ypos - lastPosY ); glm::vec3 axis = glm::vec3( yoffset, xoffset, 0.f ); axis = glm::normalize( axis ); const float angle = glm::length( glm::vec2( xoffset, yoffset ) ) * 0.005f; glm::quat quaternion = glm::angleAxis( angle, axis ); glm::mat4 transform = glm::mat4_cast( quaternion ); mGraphicsMeshManager->mModelMatrix = transform * mGraphicsMeshManager->mModelMatrix; } // Handle translation movements if ( mouseButtonRightStatus == GLFW_PRESS && keyStatus == GLFW_PRESS ) { mCamera->truck( -0.05f * ( xpos - lastPosX ) ); mCamera->pedestal( 0.05f * ( ypos - lastPosY ) ); } // Handle rotation movements if ( mouseButtonRightStatus == GLFW_PRESS && keyShiftStatus == GLFW_PRESS ) { const float xoffset = static_cast< float >( xpos - lastPosX ); const float yoffset = static_cast< float >( ypos - lastPosY ); mGraphicsPPTBF->setShiftX( mGraphicsPPTBF->getShiftX() + xoffset * 0.025f ); mGraphicsPPTBF->setShiftY( mGraphicsPPTBF->getShiftY() + yoffset * 0.025f ); mPPTBFUpdateRequested = true; } if ( mouseButtonLeftStatus == GLFW_PRESS && keyShiftStatus == GLFW_PRESS ) { const float angleOffset = static_cast< float >( xpos - lastPosX ); float alpha = mGraphicsPPTBF->getAlpha(); alpha /= static_cast< float >( M_PI ); alpha += angleOffset * 0.025f; alpha = glm::mod( alpha, 2.f ); mGraphicsPPTBF->setAlpha( alpha * static_cast< float >( M_PI ) ); mPPTBFUpdateRequested = true; } lastPosX = xpos; lastPosY = ypos; if ( mPPTBFUpdateRequested ) { handleRequests(); refresh(); } } /****************************************************************************** * If you wish to be notified when a mouse button is pressed or released, set a mouse button callback. * The callback function receives the mouse button, button action and modifier bits. * The action is one of GLFW_PRESS or GLFW_RELEASE. * Mouse button states for named buttons are also saved in per-window state arrays that can be polled with glfwGetMouseButton. * The returned state is one of GLFW_PRESS or GLFW_RELEASE. ******************************************************************************/ void PtViewer::mouse_button_callback( GLFWwindow* window, int button, int action, int mods ) { //printf( "\nmouse_button_callback = (%d,%d;%d)", button, action, mods ); // Call ImGui callback ImGui_ImplGlfwGL3_MouseButtonCallback( window, button, action, mods ); // Call Pt callback static_cast< PtViewer* >( glfwGetWindowUserPointer( window ) )->processMouseButtonEvent( button, action, mods ); } /****************************************************************************** * If you wish to be notified when a mouse button is pressed or released, set a mouse button callback. * The callback function receives the mouse button, button action and modifier bits. * The action is one of GLFW_PRESS or GLFW_RELEASE. * Mouse button states for named buttons are also saved in per-window state arrays that can be polled with glfwGetMouseButton. * The returned state is one of GLFW_PRESS or GLFW_RELEASE. ******************************************************************************/ void PtViewer::processMouseButtonEvent( int button, int action, int mods ) { } /****************************************************************************** * If you wish to be notified when the user scrolls, whether with a mouse wheel or touchpad gesture, set a scroll callback. * The callback function receives two-dimensional scroll offsets. * A simple mouse wheel, being vertical, provides offsets along the Y-axis. ******************************************************************************/ void PtViewer::scroll_callback( GLFWwindow* window, double xoffset, double yoffset ) { //printf( "\nscroll_callback = (%f,%f)", xoffset, yoffset ); // Call ImGui callback ImGui_ImplGlfwGL3_ScrollCallback( window, xoffset, yoffset ); // Call Pt callback static_cast< PtViewer* >( glfwGetWindowUserPointer( window ) )->processScrollEvent( xoffset, yoffset ); } /****************************************************************************** * If you wish to be notified when the user scrolls, whether with a mouse wheel or touchpad gesture, set a scroll callback. * The callback function receives two-dimensional scroll offsets. * A simple mouse wheel, being vertical, provides offsets along the Y-axis. ******************************************************************************/ void PtViewer::processScrollEvent( double xoffset, double yoffset ) { const int keyStatus = glfwGetKey( mWindow, GLFW_KEY_LEFT_CONTROL ); if ( keyStatus == GLFW_PRESS ) { mCamera->dolly( - static_cast< float >( yoffset ) * 2.5f ); } const int keyShiftStatus = glfwGetKey( mWindow, GLFW_KEY_LEFT_SHIFT ); if ( keyShiftStatus == GLFW_PRESS ) { int resolution = mGraphicsPPTBF->getResolution(); resolution += static_cast< int >( - yoffset * 10. ); resolution = glm::clamp( resolution, 1, 1000 ); mGraphicsPPTBF->setResolution( resolution ); mPPTBFUpdateRequested = true; } } /****************************************************************************** * Refresh ******************************************************************************/ void PtViewer::refresh() { // Set context // NOTE: // By default, making a context non-current implicitly forces a pipeline flush // On machines that support GL_KHR_context_flush_control, you can control whether a context performs this flush by setting the GLFW_CONTEXT_RELEASE_BEHAVIOR window hint. glfwMakeContextCurrent( getWindow() ); // Render scene render(); // Swap buffers glfwSwapBuffers( getWindow() ); } /****************************************************************************** * Initialize timer(s) ******************************************************************************/ void PtViewer::graphicsInitialization_Timer() { // Device timer glCreateQueries( GL_TIME_ELAPSED, 1, &mQueryTimeElapsed ); } /****************************************************************************** * Finalize timer(s) ******************************************************************************/ void PtViewer::graphicsFinalization_Timer() { // Device timer glDeleteQueries( 1, &mQueryTimeElapsed ); } /****************************************************************************** * Render ******************************************************************************/ void PtViewer::render() { // Rendering stage // Clear framebuffer ImVec4 clear_color = ImVec4( 0.45f, 0.55f, 0.60f, 1.00f ); glClearColor( clear_color.x, clear_color.y, clear_color.z, clear_color.w ); glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); // Render scene // Cannot draw with a bounded VAO in GL Core profile...? if ( mUseGLCoreProfile ) { glBindVertexArray( mGLCoreProfileVAO ); } glClearColor( clear_color.x, clear_color.y, clear_color.z, clear_color.w ); // Render PPTBF //mGraphicsPPTBF->render(); // Cannot draw with a bounded VAO in GL Core profile...? if ( mUseGLCoreProfile ) { glBindVertexArray( mGLCoreProfileVAO ); } // Render 3D mesh glEnable( GL_DEPTH_TEST ); //glBindSampler( 0, 0 ); mGraphicsMeshManager->render( mCamera ); glDisable( GL_DEPTH_TEST ); // PPTBF { GLint last_viewport[ 4 ]; glGetIntegerv( GL_VIEWPORT, last_viewport ); int width, height; glfwGetWindowSize( mWindow, &width, &height ); const int mapSize = 300; glViewport( width - mapSize, mapSize, mapSize, mapSize ); glDisable( GL_DEPTH_TEST ); // Set shader program PtShaderProgram* shaderProgram = mGraphicsPPTBF->editPPTBFViewerShaderProgram(); shaderProgram->use(); { // Set texture(s) //glBindTextureUnit( 0/*unit*/, mPPTBFTexture ); // TEST: display separable pass // - window function //const GLuint* const windowCellularTextureID = mWindowCellular->getTextureID(); //glBindTextureUnit( 0/*unit*/, *windowCellularTextureID ); //// - feature function //const GLuint* const featureTextureID = mFeatureManager->getTextureID(); //glBindTextureUnit( 0/*unit*/, *featureTextureID ); // - PPTBF (compositing) glBindTextureUnit( 0/*unit*/, mGraphicsPPTBF->mPPTBFTexture ); // Set uniform(s) shaderProgram->set( 0, "uTexture" ); // Note: this uniform never changes => can be set after shaderprogram::link() // Draw command(s) glDrawArrays( GL_TRIANGLES, 0, 3 ); } // Reset GL state(s) //glBindTexture( GL_TEXTURE_2D, 0 ); PtShaderProgram::unuse(); glViewport( last_viewport[ 0 ], last_viewport[ 1 ], static_cast< GLsizei >( last_viewport[ 2 ] ), static_cast< GLsizei >( last_viewport[ 3 ] ) ); glEnable( GL_DEPTH_TEST ); } // Binary structure map if ( mUIShowHistogram ) { // Binary structure map //glBlitFramebuffer(, ); //glBlitNamedFramebuffer( mGraphicsPPTBF->mPPTBFFrameBuffer, 0 ); GLint last_viewport[ 4 ]; glGetIntegerv( GL_VIEWPORT, last_viewport ); int width, height; glfwGetWindowSize( mWindow, &width, &height ); //glfwGetFramebufferSize( mWindow, &width, &height ); const int mapSize = 300; //glViewport( 250, 250, static_cast< GLsizei >( static_cast< float >( mapSize ) * /*screen ratio*/( static_cast< float >( width ) / static_cast< float >( height ) ) ), mapSize ); glViewport( width - mapSize, 0, mapSize, mapSize ); glDisable( GL_DEPTH_TEST ); // Render PPTBF // - render PPTBF texture PtShaderProgram* binaryStructureMapShaderProgram = mGraphicsPPTBF->editBinaryStructureMapShaderProgram(); binaryStructureMapShaderProgram->use(); glBindTextureUnit( 0/*unit*/, mGraphicsPPTBF->mPPTBFTexture ); binaryStructureMapShaderProgram->set( 0, "uTexture" ); // Note: this uniform never changes => can be set after shaderprogram::link() binaryStructureMapShaderProgram->set( mBinaryStructureMapThreshold, "uThreshold" ); // Draw command(s) glDrawArrays( GL_TRIANGLES, 0, 3 ); // Reset GL state(s) //glBindTexture( GL_TEXTURE_2D, 0 ); PtShaderProgram::unuse(); glViewport( last_viewport[ 0 ], last_viewport[ 1 ], static_cast< GLsizei >( last_viewport[ 2 ] ), static_cast< GLsizei >( last_viewport[ 3 ] ) ); glEnable( GL_DEPTH_TEST ); } // Cannot draw with a bounded VAO in GL Core profile...? if ( mUseGLCoreProfile ) { glBindVertexArray( 0 ); } // Render GUI renderGUI(); } /****************************************************************************** * Render HUD ******************************************************************************/ void PtViewer::renderHUD() { } /****************************************************************************** * Render GUI ******************************************************************************/ void PtViewer::renderGUI() { // Check whether or not to display the user interface if ( mShowUI ) { bool uiFrame_ModelTransform_show = true; bool uiFrame_Deformations_NonStationarity_and_Mixtures_show = true; bool uiFrame_PointProcess_show = true; bool uiFrame_WindowFunction_show = true; bool uiFrame_FeatureFunction_show = true; bool uiFrame_TextureSynthesis_show = true; bool uiFrame_GlobalSettings_show = true; bool uiFrame_FPS_show = true; bool uiFrame_Performance_show = true; bool uiFrame_BinaryStructureMap_show = true; bool uiFrame_Rendering_show = true; // ImGui new frame ImGui_ImplGlfwGL3_NewFrame(); // for UI enhancing... //bool show_demo_window = true; //ImGui::SetNextWindowPos( ImVec2( 20, 20 ), ImGuiCond_FirstUseEver ); // Normally user code doesn't need/want to call this because positions are saved in .ini file anyway. Here we just want to make the demo initial state a bit more friendly! //ImGui::ShowTestWindow( &show_demo_window ); // Rendering Parameters if ( uiFrame_Rendering_show ) { ImGui::Begin( "Rendering Parameters", &uiFrame_Rendering_show ); { // Force the window size to be adjusted to its content ImGui::SetWindowSize( ImVec2( 0.f,0.f ) ); // Start widget //ImGui::Begin( "Global Settings", &uiFrame_GlobalSettings_show ); if ( ImGui::CollapsingHeader( "Mesh Settings" ) ) { // slider will be 65% of the window width (this is the default) ImGui::PushItemWidth( ImGui::GetWindowWidth() * 0.4f ); // Output size static int meshType = 0; bool meshWidgetPressed = false; if ( ImGui::RadioButton( "grid##Mesh", &meshType, 0 ) ) { meshWidgetPressed = true; } if ( ImGui::RadioButton( "wave##Mesh", &meshType, 1 ) ) { meshWidgetPressed = true; } if ( ImGui::RadioButton( "cylinder##Mesh", &meshType, 2 ) ) { meshWidgetPressed = true; } if ( ImGui::RadioButton( "torus##Mesh", &meshType, 3 ) ) { meshWidgetPressed = true; } if ( ImGui::RadioButton( "sphere##Mesh", &meshType, 4 ) ) { meshWidgetPressed = true; } // Apply modification if any if ( meshWidgetPressed ) { mGraphicsMeshManager->setMeshType( static_cast< PtGraphicsMeshManager::MeshType >( meshType ) ); } } if ( ImGui::CollapsingHeader( "Rendering Mode" ) ) { // Output size static int renderingMode = 0; bool renderingModeWidgetPressed = false; if ( ImGui::RadioButton( "pptfb##RenderingMode", &renderingMode, 0 ) ) { renderingModeWidgetPressed = true; } if ( ImGui::RadioButton( "binaryMap##RenderingMode", &renderingMode, 1 ) ) { renderingModeWidgetPressed = true; } // Apply modification if any if ( renderingModeWidgetPressed ) { mGraphicsPPTBF->setRenderingMode( static_cast< PtGraphicsPPTBF::ERenderingMode >( renderingMode ) ); switch ( static_cast< PtGraphicsPPTBF::ERenderingMode >( renderingMode ) ) { case PtGraphicsPPTBF::ERenderingMode::ePPTBF: mGraphicsMeshManager->setPPTBFTexture( mGraphicsPPTBF->mPPTBFTexture ); break; case PtGraphicsPPTBF::ERenderingMode::eBinaryMap: mGraphicsMeshManager->setPPTBFTexture( mGraphicsPPTBF->mThresholdTexture); break; default: mGraphicsMeshManager->setPPTBFTexture( mGraphicsPPTBF->mPPTBFTexture ); break; } } } } ImGui::End(); } // Binary structure map if ( uiFrame_BinaryStructureMap_show ) { ImGui::Begin( "Binary Structure Map", &uiFrame_BinaryStructureMap_show ); { // Force the window size to be adjusted to its content ImGui::SetWindowSize( ImVec2( 0.f,0.f ) ); ImGui::Checkbox( "BinaryHistograms", &mUIShowHistogram ); if ( mUIShowHistogram ) { // Nb bins if ( ImGui::SliderInt( "Nb bins", &uiBinaryStructureMap_nbBins, 1, 1000 ) ) { mHistogramUpdateRequested = true; } // Histograms const int width = mGraphicsPPTBF->getWidth(); const int height = mGraphicsPPTBF->getHeight(); #if 0 /*std::vector< float > histogram; std::vector< float > CDF;*/ mGraphicsHistogram->getHistogram( histogram, CDF, width, height ); //, todo: move that in hendleRequest() [outside rendering stage] #endif ImGui::PlotHistogram( "Histogram", histogram.data(), static_cast< int >( histogram.size() ), 0, NULL, 0, FLT_MAX, ImVec2( 100, 100 ) ); const int nbPixels = width * height; /*for ( auto& v : CDF ) { v /= static_cast< float >( nbPixels ); }*/ ImGui::PlotHistogram( "CDF", CDF.data(), static_cast< int >( CDF.size() ), 0, NULL, 0.0, /*1.0*/FLT_MAX, ImVec2( 100, 100 ) ); // Threshold if ( ImGui::SliderInt( "Threshold", &uiBinaryStructureMap_threshold, 0, 100 ) ) { mGraphicsPPTBF->setThreshold( uiBinaryStructureMap_threshold * 0.01f ); mHistogramUpdateRequested = true; } ImGui::Text( "Binary structure map: %.6f", mBinaryStructureMapThreshold ); } } ImGui::End(); } bool uiFrame_PPTBFDesigner_show = true; ImGui::Begin( "PPTBF Designer", &uiFrame_PPTBFDesigner_show ); { // Force the window size to be adjusted to its content //ImGui::SetWindowSize( ImVec2( 0.f,0.f ) ); // Tip: if we don't call ImGui::Begin()/ImGui::End() the widgets automatically appears in a window called "Debug". if ( uiFrame_GlobalSettings_show ) { // Start widget //ImGui::Begin( "Global Settings", &uiFrame_GlobalSettings_show ); if ( ImGui::CollapsingHeader( "Global Settings" ) ) { // slider will be 65% of the window width (this is the default) ImGui::PushItemWidth( ImGui::GetWindowWidth() * 0.4f ); // Output size int synthesisSize[ 2 ] = { mGraphicsPPTBF->getWidth(), mGraphicsPPTBF->getHeight() }; if ( ImGui::InputInt2( "size", synthesisSize ) ) { mGraphicsPPTBF->setWidth( synthesisSize[ 0 ] ); mGraphicsPPTBF->setHeight( synthesisSize[ 1 ] ); mGraphicsPPTBF->setImageWidth( synthesisSize[ 0 ] ); mGraphicsPPTBF->setImageHeight( synthesisSize[ 1 ] ); mGraphicsPPTBF->onSizeModified( synthesisSize[ 0 ], synthesisSize[ 1 ] ); mPPTBFUpdateRequested = true; } //// Debug //if ( ImGui::TreeNode( "Debug" ) ) //{ // ImGui::Checkbox( "Use Window Function", &uiGlobalSettings_useWindowFunction ); // ImGui::Checkbox( "Use Feature Function", &uiGlobalSettings_useFeatureFunction ); // // ImGui::TreePop(); //} // End widget //ImGui::End(); } } if ( ImGui::CollapsingHeader( "PPTBF Parameters" ) ) { // Tip: if we don't call ImGui::Begin()/ImGui::End() the widgets automatically appears in a window called "Debug". if ( uiFrame_ModelTransform_show ) { // Start widget //ImGui::Begin( "Deformations, Non-Stationarity and Mixtures Parameters", &uiFrame_Deformations_NonStationarity_and_Mixtures_show ); //if ( ImGui::CollapsingHeader( "\tDeformations, Non-Stationarity and Mixtures" ) ) if ( ImGui::CollapsingHeader( "\tModel Transform" ) ) { // slider will be 65% of the window width (this is the default) ImGui::PushItemWidth( ImGui::GetWindowWidth() * 0.4f ); //if ( ImGui::TreeNode( "Spatial Deformation" ) ) //{ // RESOL int modelTransformResolution = mGraphicsPPTBF->getResolution(); if ( ImGui::SliderInt( "resolution", &modelTransformResolution, 1, 1000 ) ) { mGraphicsPPTBF->editPPTBFGeneratorShaderProgram()->use(); mGraphicsPPTBF->setResolution( modelTransformResolution ); PtShaderProgram::unuse(); mPPTBFUpdateRequested = true; } // alpha float modelTransformRotation = mGraphicsPPTBF->getAlpha(); modelTransformRotation /= static_cast< float >( M_PI ); if ( ImGui::SliderFloat( "rotation", &modelTransformRotation, 0.f, 2.f ) ) { mGraphicsPPTBF->editPPTBFGeneratorShaderProgram()->use(); mGraphicsPPTBF->setAlpha( modelTransformRotation * static_cast< float >( M_PI ) ); PtShaderProgram::unuse(); mPPTBFUpdateRequested = true; } // rescalex float modelTransformAspectRatio = mGraphicsPPTBF->getRescalex(); if ( ImGui::SliderFloat( "aspect ratio", &modelTransformAspectRatio, 0.01f, 10.f ) ) { mGraphicsPPTBF->editPPTBFGeneratorShaderProgram()->use(); mGraphicsPPTBF->setRescalex( modelTransformAspectRatio ); PtShaderProgram::unuse(); mPPTBFUpdateRequested = true; } //ImGui::TreePop(); //} } } // Tip: if we don't call ImGui::Begin()/ImGui::End() the widgets automatically appears in a window called "Debug". if ( uiFrame_Deformations_NonStationarity_and_Mixtures_show ) { // Start widget //ImGui::Begin( "Deformations, Non-Stationarity and Mixtures Parameters", &uiFrame_Deformations_NonStationarity_and_Mixtures_show ); //if ( ImGui::CollapsingHeader( "\tDeformations, Non-Stationarity and Mixtures" ) ) if ( ImGui::CollapsingHeader( "\tDeformations" ) ) { // slider will be 65% of the window width (this is the default) ImGui::PushItemWidth( ImGui::GetWindowWidth() * 0.4f ); //if ( ImGui::TreeNode( "Spatial Deformation" ) ) //{ // Spatial deformation //float spatialDeformation[ 3 ] = { uiDefNonStaAndMix_spatialDeformation.x, uiDefNonStaAndMix_spatialDeformation.y, uiDefNonStaAndMix_spatialDeformation.z }; //ImGui::SliderFloat3( "Multi-band amplitudes", spatialDeformation, 0.f, 1.f ); float deformationTurbulenceAmplitude0 = mGraphicsPPTBF->getTurbulenceAmplitude0(); if ( ImGui::SliderFloat( "base amplitude##deformation", &deformationTurbulenceAmplitude0, 0.f, 0.25f ) ) { mGraphicsPPTBF->editPPTBFGeneratorShaderProgram()->use(); mGraphicsPPTBF->setTurbulenceAmplitude0( deformationTurbulenceAmplitude0 ); PtShaderProgram::unuse(); mPPTBFUpdateRequested = true; } float deformationTurbulenceAmplitude1 = mGraphicsPPTBF->getTurbulenceAmplitude1(); if ( ImGui::SliderFloat( "gain##deformation", &deformationTurbulenceAmplitude1, 0.f, 4.f ) ) { mGraphicsPPTBF->editPPTBFGeneratorShaderProgram()->use(); mGraphicsPPTBF->setTurbulenceAmplitude1( deformationTurbulenceAmplitude1 ); PtShaderProgram::unuse(); mPPTBFUpdateRequested = true; } float deformationTurbulenceAmplitude2 = mGraphicsPPTBF->getTurbulenceAmplitude2(); if ( ImGui::SliderFloat( "A2##deformation", &deformationTurbulenceAmplitude2, 0.f, 1.f ) ) { mGraphicsPPTBF->editPPTBFGeneratorShaderProgram()->use(); mGraphicsPPTBF->setTurbulenceAmplitude2( deformationTurbulenceAmplitude2 ); PtShaderProgram::unuse(); mPPTBFUpdateRequested = true; } /*uiDefNonStaAndMix_spatialDeformation.x = spatialDeformation[ 0 ]; uiDefNonStaAndMix_spatialDeformation.y = spatialDeformation[ 1 ]; uiDefNonStaAndMix_spatialDeformation.z = spatialDeformation[ 2 ];*/ // ImGui::TreePop(); //} } } // Tip: if we don't call ImGui::Begin()/ImGui::End() the widgets automatically appears in a window called "Debug". if ( uiFrame_PointProcess_show ) { // Start widget //ImGui::Begin( "Point Process Parameters", &uiFrame_PointProcess_show ); if ( ImGui::CollapsingHeader( "\tPoint Process" ) ) { // slider will be 65% of the window width (this is the default) ImGui::PushItemWidth( ImGui::GetWindowWidth() * 0.4f ); // if ( ImGui::TreeNode( "Pavement" ) ) // { // Tiling type //if ( ImGui::Combo( "tiling type", &uiPointProcess_tilingType, "regular\0irregular\0cross\0bisquare\0irregular_x\0irregular_y\0\0" ) ) // Combo using values packed in a single constant string (for really quick combo) int pointProcessTilingType = mGraphicsPPTBF->getTilingType(); if ( ImGui::SliderInt( "tiling type", &pointProcessTilingType, 0, 17 ) ) { mGraphicsPPTBF->editPPTBFGeneratorShaderProgram()->use(); mGraphicsPPTBF->setTilingType( pointProcessTilingType ); PtShaderProgram::unuse(); mPPTBFUpdateRequested = true; } // Jittering float pointProcessJittering = mGraphicsPPTBF->getJittering(); if ( ImGui::SliderFloat( "jittering", &pointProcessJittering, 0.f, 1.f ) ) { mGraphicsPPTBF->editPPTBFGeneratorShaderProgram()->use(); mGraphicsPPTBF->setJittering( pointProcessJittering ); PtShaderProgram::unuse(); mPPTBFUpdateRequested = true; } // ImGui::TreePop(); //} //if ( ImGui::TreeNode( "Repulsive Forces" ) ) //{ // // Number of relaxation iterations (repulsive force) // if ( ImGui::SliderInt( "nb relaxation iterations", &uiPointProcess_nbRelaxationIterations, 0, 5 ) ) // { // if ( uiPointProcess_nbRelaxationIterations != mGraphicsPPTBF->getNbRelaxationIterations() ) // { // mGraphicsPPTBF->editPPTBFGeneratorShaderProgram()->use(); // mGraphicsPPTBF->setNbRelaxationIterations( uiPointProcess_nbRelaxationIterations ); // PtShaderProgram::unuse(); // mPPTBFUpdateRequested = true; // } // } // ImGui::TreePop(); //} // End widget //ImGui::End(); } } // Tip: if we don't call ImGui::Begin()/ImGui::End() the widgets automatically appears in a window called "Debug". if ( uiFrame_WindowFunction_show ) { // Start widget //ImGui::Begin( "Window Function Parameters", &uiFrame_WindowFunction_show ); if ( ImGui::CollapsingHeader( "\tWindow Function" ) ) { // slider will be 65% of the window width (this is the default) ImGui::PushItemWidth( ImGui::GetWindowWidth() * 0.4f ); // Window blend float windowBlend = mGraphicsPPTBF->getWindowBlend(); if ( ImGui::SliderFloat( "blend##Window", &windowBlend, 0.f, 1.f ) ) { mGraphicsPPTBF->setWindowBlend( windowBlend ); mPPTBFUpdateRequested = true; } // Display type { ImGui::SameLine(); std::string windowTypename = ""; if ( windowBlend == 0.f ) windowTypename = "[regular]"; else if ( windowBlend == 1.f ) windowTypename = "[cellular]"; else windowTypename = "[mix regular/cellular]"; ImGui::TextColored( ImVec4( 0.f, 1.f, 0.f, 1.f ), windowTypename.c_str() ); } // Window norm float windowNorm = mGraphicsPPTBF->getWindowNorm(); if ( ImGui::SliderFloat( "norm##Window", &windowNorm, 1.f, 3.f ) ) { mGraphicsPPTBF->setWindowNorm( windowNorm ); mPPTBFUpdateRequested = true; } // Gaussian Window if ( ImGui::TreeNode( "Cellular" ) ) { // Window larp float windowLarp = mGraphicsPPTBF->getWindowLarp(); if ( ImGui::SliderFloat( "larp##Window", &windowLarp, 0.f, 1.f ) ) { mGraphicsPPTBF->setWindowLarp( windowLarp ); mPPTBFUpdateRequested = true; } // Window arity float windowArity = mGraphicsPPTBF->getWindowArity(); if ( ImGui::SliderFloat( "arity##Window", &windowArity, 2.f, 10.f ) ) { mGraphicsPPTBF->setWindowArity( windowArity ); mPPTBFUpdateRequested = true; } // Window smooth float windowSmooth = mGraphicsPPTBF->getWindowSmooth(); if ( ImGui::SliderFloat( "smooth##Window", &windowSmooth, 0.f, 2.f ) ) { mGraphicsPPTBF->setWindowSmooth( windowSmooth ); mPPTBFUpdateRequested = true; } // Window sigwcell float windowSigwcell = mGraphicsPPTBF->getWindowSigwcell(); if ( ImGui::SliderFloat( "sigwcell##Window", &windowSigwcell, 0.01f, 4.f ) ) { mGraphicsPPTBF->setWindowSigwcell( windowSigwcell ); mPPTBFUpdateRequested = true; } ImGui::TreePop(); } // Gaussian Window if ( ImGui::TreeNode( "Regular" ) ) { // Window shape int windowShape = mGraphicsPPTBF->getWindowShape(); if ( ImGui::SliderInt( "shape##Window", &windowShape, 0, 3 ) ) { mGraphicsPPTBF->setWindowShape( windowShape ); mPPTBFUpdateRequested = true; } // Display type { ImGui::SameLine(); std::string windowTypename = ""; if ( windowShape == 0 ) windowTypename = "[normalized tapered cosine]"; else if ( windowShape == 1 ) windowTypename = "[clamped gaussian]"; else if ( windowShape == 2 ) windowTypename = "[triangular]"; else if ( windowShape == 3 ) windowTypename = "[tapered cosine]"; else windowTypename = "[triangular]"; ImGui::TextColored( ImVec4( 0.f, 1.f, 0.f, 1.f ), windowTypename.c_str() ); } ImGui::TreePop(); } // End widget //ImGui::End(); } } // Tip: if we don't call ImGui::Begin()/ImGui::End() the widgets automatically appears in a window called "Debug". if ( uiFrame_FeatureFunction_show ) { // Start widget //ImGui::Begin( "Feature Function Parameters", &uiFrame_FeatureFunction_show ); if ( ImGui::CollapsingHeader( "\tFeature Function" ) ) { // slider will be 65% of the window width (this is the default) ImGui::PushItemWidth( ImGui::GetWindowWidth() * 0.4f ); // Bombing flag int featureType = mGraphicsPPTBF->getBombingFlag(); if ( ImGui::SliderInt( "type##FeatureFunction", &featureType, 0, 8 ) ) // max ?? { mGraphicsPPTBF->editPPTBFGeneratorShaderProgram()->use(); mGraphicsPPTBF->setBombingFlag( featureType ); PtShaderProgram::unuse(); mPPTBFUpdateRequested = true; } // Display type { ImGui::SameLine(); std::string featureTypename = ""; if ( featureType == 0 ) featureTypename = "[constant]"; else if ( featureType == 1 ) featureTypename = "[Gabor random]"; else if ( featureType == 2 ) featureTypename = "[Gabor]"; else if ( featureType == 3 ) featureTypename = "[bombing]"; else if ( featureType == 4 ) featureTypename = "[Voronoise]"; else if ( featureType == 5 ) featureTypename = "[USER Markov Chain network]"; else featureTypename = "[not yet...]"; ImGui::TextColored( ImVec4( 0.f, 1.f, 0.f, 1.f ), featureTypename.c_str() ); } // Feature stripes if ( ImGui::TreeNode( "Appearance" ) ) { // Gaussian window norm float featureWinfeatcorrel = mGraphicsPPTBF->getFeatureWinfeatcorrel(); if ( ImGui::SliderFloat( "Winfeatcorrel##FeatureFunction", &featureWinfeatcorrel, 0.f, 1.f ) ) { mGraphicsPPTBF->editPPTBFGeneratorShaderProgram()->use(); mGraphicsPPTBF->setFeatureWinfeatcorrel( featureWinfeatcorrel ); PtShaderProgram::unuse(); mPPTBFUpdateRequested = true; } // Feature phase shift float featurePhaseShift = mGraphicsPPTBF->getFeaturePhaseShift(); featurePhaseShift /= ( static_cast< float >( M_PI ) * 0.5f ); if ( ImGui::SliderFloat( "phase shift", &featurePhaseShift, 0.f, 1.f ) ) { mGraphicsPPTBF->editPPTBFGeneratorShaderProgram()->use(); mGraphicsPPTBF->setFeaturePhaseShift( featurePhaseShift * ( static_cast< float >( M_PI ) * 0.5f ) ); PtShaderProgram::unuse(); mPPTBFUpdateRequested = true; } // Gaussian window norm float featureNorm = mGraphicsPPTBF->getFeatureNorm(); if ( ImGui::SliderFloat( "norm##FeatureFunction", &featureNorm, 1.f, 3.f ) ) { mGraphicsPPTBF->editPPTBFGeneratorShaderProgram()->use(); mGraphicsPPTBF->setFeatureNorm( featureNorm ); PtShaderProgram::unuse(); mPPTBFUpdateRequested = true; } // Gaussian window norm float featureAnisotropy = mGraphicsPPTBF->getFeatureAnisotropy(); if ( ImGui::SliderFloat( "anisotropy##FeatureFunction", &featureAnisotropy, 0.f, 5.f ) ) { mGraphicsPPTBF->editPPTBFGeneratorShaderProgram()->use(); mGraphicsPPTBF->setFeatureAnisotropy( featureAnisotropy ); PtShaderProgram::unuse(); mPPTBFUpdateRequested = true; } // Gabor decay float featureSigcos = mGraphicsPPTBF->getGaborDecay(); if ( ImGui::SliderFloat( "sigcos##featureGaussian", &featureSigcos, 0.f, 10.f ) ) { mGraphicsPPTBF->editPPTBFGeneratorShaderProgram()->use(); mGraphicsPPTBF->setGaborDecay( featureSigcos ); PtShaderProgram::unuse(); mPPTBFUpdateRequested = true; } // Gabor decay variation float featureSigcosvar = mGraphicsPPTBF->getGaborDecayJittering(); if ( ImGui::SliderFloat( "sigcosvar##featureGaussian", &featureSigcosvar, 0.f, 1.f ) ) { mGraphicsPPTBF->editPPTBFGeneratorShaderProgram()->use(); mGraphicsPPTBF->setGaborDecayJittering( featureSigcosvar ); PtShaderProgram::unuse(); mPPTBFUpdateRequested = true; } ImGui::TreePop(); } // Feature stripes if ( ImGui::TreeNode( "Kernels" ) ) { // Min number of Gabor kernels int featureMinNbKernels = mGraphicsPPTBF->getMinNbGaborKernels(); int featureMaxNbKernels = mGraphicsPPTBF->getMaxNbGaborKernels(); if ( ImGui::SliderInt( "nb min", &featureMinNbKernels, 0, 8 ) ) { featureMinNbKernels = glm::clamp( featureMinNbKernels, 0, featureMaxNbKernels ); mGraphicsPPTBF->editPPTBFGeneratorShaderProgram()->use(); mGraphicsPPTBF->setMinNbGaborKernels( featureMinNbKernels ); PtShaderProgram::unuse(); mPPTBFUpdateRequested = true; } // Max number of Gabor kernels if ( ImGui::SliderInt( "nb max", &featureMaxNbKernels, 0, 8 ) ) { featureMaxNbKernels = glm::clamp( featureMaxNbKernels, featureMinNbKernels, 8 ); mGraphicsPPTBF->editPPTBFGeneratorShaderProgram()->use(); mGraphicsPPTBF->setMaxNbGaborKernels( featureMaxNbKernels ); PtShaderProgram::unuse(); mPPTBFUpdateRequested = true; } ImGui::TreePop(); } // Feature stripes if ( ImGui::TreeNode( "Stripes" ) ) { // Gabor stripes frequency int featureStripesFrequency = mGraphicsPPTBF->getGaborStripesFrequency(); if ( ImGui::SliderInt( "frequency##featureStripes", &featureStripesFrequency, 0, 16 ) ) { mGraphicsPPTBF->editPPTBFGeneratorShaderProgram()->use(); mGraphicsPPTBF->setGaborStripesFrequency( featureStripesFrequency ); PtShaderProgram::unuse(); mPPTBFUpdateRequested = true; } // Gabor stripes thickness float featureStripesThickness = mGraphicsPPTBF->getGaborStripesThickness(); if ( ImGui::SliderFloat( "thickness##featureStripes", &featureStripesThickness, 0.001f, 1.f ) ) { mGraphicsPPTBF->editPPTBFGeneratorShaderProgram()->use(); mGraphicsPPTBF->setGaborStripesThickness( featureStripesThickness ); PtShaderProgram::unuse(); mPPTBFUpdateRequested = true; } // Gabor stripes curvature float featureStripesCurvature = mGraphicsPPTBF->getGaborStripesCurvature(); if ( ImGui::SliderFloat( "curvature##featureStripes", &featureStripesCurvature, 0.f, 1.f ) ) { mGraphicsPPTBF->editPPTBFGeneratorShaderProgram()->use(); mGraphicsPPTBF->setGaborStripesCurvature( featureStripesCurvature ); PtShaderProgram::unuse(); mPPTBFUpdateRequested = true; } // Gabor stripes orientation float featureStripesOrientation = mGraphicsPPTBF->getGaborStripesOrientation(); featureStripesOrientation /= static_cast< float >( M_PI ); if ( ImGui::SliderFloat( "orientation##featureStripes", &featureStripesOrientation, 0.f, 0.5f ) ) { mGraphicsPPTBF->editPPTBFGeneratorShaderProgram()->use(); mGraphicsPPTBF->setGaborStripesOrientation( featureStripesOrientation * static_cast< float >( M_PI ) ); PtShaderProgram::unuse(); mPPTBFUpdateRequested = true; } ImGui::TreePop(); } } } } //// Binary structure map //if ( uiFrame_BinaryStructureMap_show ) //{ // //ImGui::Begin( "Binary Structure Map", &uiFrame_BinaryStructureMap_show ); // if ( ImGui::CollapsingHeader( "Binary Structure Map" ) ) // { // ImGui::Checkbox( "BinaryHistograms", &mUIShowHistogram ); // if ( mUIShowHistogram ) // { // // Nb bins // if ( ImGui::SliderInt( "Nb bins", &uiBinaryStructureMap_nbBins, 1, 1000 ) ) // { // mHistogramUpdateRequested = true; // } // // Histograms // int width, height; // glfwGetWindowSize( mWindow, &width, &height ); // std::vector< float > histogram; // std::vector< float > CDF; // mGraphicsHistogram->getHistogram( histogram, CDF, width, height ); // ImGui::PlotHistogram( "Histogram", histogram.data(), static_cast< int >( histogram.size() ), 0, NULL, 0, FLT_MAX, ImVec2( 100, 100 ) ); // const int nbPixels = width * height; // for ( auto& v : CDF ) // { // v /= static_cast< float >( nbPixels ); // } // ImGui::PlotHistogram( "CDF", CDF.data(), static_cast< int >( CDF.size() ), 0, NULL, 0.0, 1.0, ImVec2( 100, 100 ) ); // // Threshold // if ( ImGui::SliderInt( "Threshold", &uiBinaryStructureMap_threshold, 0, 100 ) ) // { // float pptbfThreshold = 0.f; // float cdfThreshold = static_cast< float >( uiBinaryStructureMap_threshold ) * 0.01f; // for ( const auto v : CDF ) // { // if ( v < cdfThreshold ) // { // pptbfThreshold += ( 1.f / static_cast< float >( CDF.size() ) ); // } // else // { // break; // } // } // mBinaryStructureMapThreshold = pptbfThreshold; // //std::cout << "pptbfThreshold:" << pptbfThreshold << std::endl; // } // ImGui::Text( "Binary structure map: %.6f", mBinaryStructureMapThreshold ); // } // // //ImGui::End(); // } //} } ImGui::End(); bool show_app_fixed_overlay = true; if (show_app_fixed_overlay) showExampleAppFixedOverlay( &show_app_fixed_overlay ); // Show IMGui metrics //ImGui::ShowMetricsWindow(); //ImGui::Image((void*)(mGraphicsPPTBF->mPPTBFTexture), ImVec2(512, 512)); // Render HUD overlay (user interface) ImGui::Render(); } } /****************************************************************************** * ... ******************************************************************************/ // Demonstrate creating a simple static window with no decoration + a context-menu to choose which corner of the screen to use. void PtViewer::showExampleAppFixedOverlay( bool* p_open ) { const float DISTANCE = 10.0f; //ImGui::PushStyleColor(ImGuiCol_WindowBg, ImVec4(0.0f, 0.0f, 0.0f, 0.3f)); // Transparent background ImGui::PushStyleColor(ImGuiCol_WindowBg, ImVec4(0.45f, 0.55f, 0.60f, 0.75f)); // Transparent background static int corner = 2; ImVec2 window_pos = ImVec2((corner & 1) ? ImGui::GetIO().DisplaySize.x - DISTANCE : DISTANCE, (corner & 2) ? ImGui::GetIO().DisplaySize.y - DISTANCE : DISTANCE); ImVec2 window_pos_pivot = ImVec2((corner & 1) ? 1.0f : 0.0f, (corner & 2) ? 1.0f : 0.0f); ImGui::SetNextWindowPos(window_pos, ImGuiCond_Always, window_pos_pivot); if (ImGui::Begin("Mouse Info", p_open, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoSavedSettings)) { //ImGui::Text("Simple overlay\nin the corner of the screen.\n(right-click to change position)"); //ImGui::Separator(); //ImGui::Text("Mouse Position: (%.1f,%.1f)", ImGui::GetIO().MousePos.x, ImGui::GetIO().MousePos.y); ImGui::Text("Mouse Position: (%d,%d)", static_cast< int >( ImGui::GetIO().MousePos.x ), static_cast< int >( ImGui::GetIO().MousePos.y ) ); /*if (ImGui::BeginPopupContextWindow()) { if (ImGui::MenuItem("Top-left", NULL, corner == 0)) corner = 0; if (ImGui::MenuItem("Top-right", NULL, corner == 1)) corner = 1; if (ImGui::MenuItem("Bottom-left", NULL, corner == 2)) corner = 2; if (ImGui::MenuItem("Bottom-right", NULL, corner == 3)) corner = 3; ImGui::EndPopup(); }*/ ImGui::End(); } static int corner2 = 1; window_pos = ImVec2((corner2 & 1) ? ImGui::GetIO().DisplaySize.x - DISTANCE : DISTANCE, (corner2 & 2) ? ImGui::GetIO().DisplaySize.y - DISTANCE : DISTANCE); window_pos_pivot = ImVec2((corner2 & 1) ? 1.0f : 0.0f, (corner2 & 2) ? 1.0f : 0.0f); ImGui::SetNextWindowPos(window_pos, ImGuiCond_Always, window_pos_pivot); if (ImGui::Begin("Synthesis Detailed Info", p_open, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoSavedSettings)) { ImGui::Text( "Profiler" ); ImGui::Separator(); ImGui::Text(const_cast< char* >( mGraphicsPPTBF->getSynthesisInfo().str().c_str() ), static_cast< int >(ImGui::GetIO().MousePos.x), static_cast< int >(ImGui::GetIO().MousePos.y)); ImGui::End(); } int width, height; glfwGetWindowSize( mWindow, &width, &height ); //glfwGetFramebufferSize( mWindow, &width, &height ); static int corner3 = 0; window_pos = ImVec2((corner3 & 1) ? ImGui::GetIO().DisplaySize.x - DISTANCE : DISTANCE, (corner3 & 2) ? ImGui::GetIO().DisplaySize.y - DISTANCE : DISTANCE); window_pos_pivot = ImVec2((corner3 & 1) ? 1.0f : 0.0f, (corner3 & 2) ? 1.0f : 0.0f); ImGui::SetNextWindowPos(window_pos, ImGuiCond_Always, window_pos_pivot); if (ImGui::Begin("Example: Fixed Overlay", p_open, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoSavedSettings)) { ImGui::Text( "Performance" ); ImGui::Separator(); ImGui::Text( "FPS %.1f", ImGui::GetIO().Framerate ); ImGui::Text( "Frame %.3f ms", 1000.0f / ImGui::GetIO().Framerate ); ImGui::Text( "Window %dx%d", width, height ); ImGui::Separator(); //ImGui::Text( "Exemplar %dx%d", mGraphicsSynthesizer->getExemplarWidth(), mGraphicsSynthesizer->getExemplarHeight() ); //ImGui::Text( "Output %dx%d", mGraphicsSynthesizer->getWidth(), mGraphicsSynthesizer->getHeight() ); //ImGui::Text( "Synthesis %5.3f ms", mGraphicsSynthesizer->getSynthesisTime() ); // Timer ImGui::Checkbox( "Timer", &uiPPTBF_timer ); if ( uiPPTBF_timer ) { // ImGui::Text( "PPTBF: [%5.3f ms]", mPPTBFGenerationTime * 1.e-6 ); // ImGui::Separator(); ImGui::Text( "Output %dx%d", mGraphicsPPTBF->getWidth(), mGraphicsPPTBF->getHeight() ); ImGui::Text( "Synthesis %5.3f ms", mGraphicsPPTBF->getSynthesisTime() ); } ImGui::End(); } ImGui::PopStyleColor(); } /****************************************************************************** * ... ******************************************************************************/ void PtViewer::synthesize() { } /****************************************************************************** * Slot called when the data model has been modified ******************************************************************************/ void PtViewer::onDataModelModified() { } /****************************************************************************** * Handle requests ******************************************************************************/ void PtViewer::handleRequests() { // Generate PPTBF // - check if PPTBF computation is requested (Update UI edition flag) if ( mPPTBFUpdateRequested ) { mPPTBFUpdateRequested = false; // TEST // Compute PPTBF //mGraphicsPPTBF->setTime( static_cast< float >( glfwGetTime() ) ); // TODO: no active program !!!!!!!!!! mGraphicsPPTBF->compute(); // Update UI edition flag //mPPTBFUpdateRequested = false; // Update UI edition flag mHistogramUpdateRequested = true; } // Binary structure map if ( mHistogramUpdateRequested ) { if ( uiBinaryStructureMap_nbBins != mGraphicsHistogram->getNbBins() ) { mGraphicsHistogram->setNbBins( uiBinaryStructureMap_nbBins ); // Resize containers const int nbBins = uiBinaryStructureMap_nbBins; histogram.clear(); // to be able to assign 0 in previous data... CDF.clear(); // to be able to assign 0 in previous data... histogram.resize( nbBins ); CDF.resize( nbBins ); } #if 0 // commented while debugging GPU bug... // GPU-based implementation if ( mUseGLCoreProfile ) { glBindVertexArray( mGLCoreProfileVAO ); } // Generate PPTBF histogram //int width, height; //glfwGetWindowSize( mWindow, &width, &height ); //glfwGetFramebufferSize( mWindow, &width, &height ); //mGraphicsHistogram->compute( mGraphicsPPTBF->mPPTBFTexture, width, height ); mGraphicsHistogram->compute( mGraphicsPPTBF->mPPTBFTexture, mGraphicsPPTBF->getWidth(), mGraphicsPPTBF->getHeight() ); //// Cannot draw with a bounded VAO in GL Core profile...? if ( mUseGLCoreProfile ) { glBindVertexArray( 0 ); } #else // Software implementation... // Retrieve data on host const int width = mGraphicsPPTBF->getWidth(); const int height = mGraphicsPPTBF->getHeight(); std::vector< float > f_pptbf( width * height ); glGetTextureImage( mGraphicsPPTBF->mPPTBFTexture, 0/*level*/, GL_RED, GL_FLOAT, sizeof( float ) * width * height, f_pptbf.data() ); // - histogram const int nbBins = mGraphicsHistogram->getNbBins(); std::fill( histogram.begin(), histogram.end(), 0.f ); std::fill( CDF.begin(), CDF.end(), 0.f ); for ( auto v : f_pptbf ) { int binID = static_cast< int >( glm::floor( v * nbBins ) ); binID = glm::clamp( binID, 0, nbBins - 1 ); histogram[ binID ]++; } // - cumulative distribution function std::partial_sum( histogram.begin(), histogram.begin() + nbBins, CDF.begin() ); // - update threshold float pptbfThreshold = 0.f; float cdfThreshold = static_cast< float >( uiBinaryStructureMap_threshold ) * 0.01f; const int nbPixels = width * height; const float scaleFactor = static_cast< float >( nbPixels ); // map CDF data to [0;1] const float cdfThresholdScaled = cdfThreshold * scaleFactor; for ( const auto v : CDF ) { //if ( ( v * scaleFactor ) <= cdfThreshold ) if ( v <= cdfThresholdScaled ) { pptbfThreshold += ( 1.f / static_cast< float >( CDF.size() ) ); } else { break; } } mBinaryStructureMapThreshold = pptbfThreshold; // Compute binary structure map mGraphicsPPTBF->computeBinaryStructureMap(); #endif // Update histogram edition flag mHistogramUpdateRequested = false; } }
69,401
C++
.cpp
1,645
38.282067
244
0.636982
ASTex-ICube/semiproctex
39
8
2
LGPL-2.1
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,916
PtApplication.cpp
ASTex-ICube_semiproctex/PPTBF_Structures_Src/Tools/PtBDDGenerator/PtApplication.cpp
/* * Publication: Semi-Procedural Textures Using Point Process Texture Basis Functions * Authors: anonymous * * Code author: Pascal Guehl * * anonymous * anonymous */ /** * @version 1.0 */ #include "PtApplication.h" /****************************************************************************** ******************************* INCLUDE SECTION ****************************** ******************************************************************************/ // STL #include <iostream> // Project #include "PtGraphicsPPTBF.h" #include "PtViewer.h" #include <PtModelLibrary.h> #include <PtGraphicsLibrary.h> /****************************************************************************** ****************************** NAMESPACE SECTION ***************************** ******************************************************************************/ // Project using namespace Pt; using namespace PtGraphics; using namespace PtGUI; // STL using namespace std; /****************************************************************************** ************************* DEFINE AND CONSTANT SECTION ************************ ******************************************************************************/ /** * The unique instance of the singleton. */ PtApplication* PtApplication::msInstance = nullptr; /****************************************************************************** ***************************** TYPE DEFINITION ******************************** ******************************************************************************/ /****************************************************************************** ***************************** METHOD DEFINITION ****************************** ******************************************************************************/ /****************************************************************************** * Get the unique instance. * * @return the unique instance ******************************************************************************/ PtApplication& PtApplication::get() { if ( msInstance == nullptr ) { msInstance = new PtApplication(); } return *msInstance; } /****************************************************************************** * Default constructor ******************************************************************************/ PtApplication::PtApplication() : mMainWindow( nullptr ) , mPPTBFParameterFilename() { // User interface mMainWindow = new PtViewer(); } /****************************************************************************** * Destructor ******************************************************************************/ PtApplication::~PtApplication() { // User interface delete mMainWindow; } /****************************************************************************** * Initialize ******************************************************************************/ bool PtApplication::initialize( const char* const pWorkingDirectory ) { bool statusOK = false; statusOK = Pt::PtDataModelLibrary::initialize( pWorkingDirectory ); if ( ! statusOK ) { return false; } statusOK = PtGraphics::PtGraphicsLibrary::initialize( pWorkingDirectory ); if ( ! statusOK ) { return false; } // Initialize the GLFW library initializeGLFW(); // Initialize windows // - at least, create one graphics context initializeWindows(); // Initialize GL library initializeGL(); // Initialize user interface //initializeImGuiUserInterface(); // already done in MainWindow... return true; } /****************************************************************************** * Finalize ******************************************************************************/ void PtApplication::finalize() { // Finalize the GLFW library finalizeGLFW(); } /****************************************************************************** * Initialize GLFW ******************************************************************************/ void PtApplication::initializeGLFW() { // Initialize GLFW library if ( ! glfwInit() ) { // Initialization failed exit( EXIT_FAILURE ); } // Set error callback glfwSetErrorCallback( error_callback ); } /****************************************************************************** * Finalize GLFW ******************************************************************************/ void PtApplication::finalizeGLFW() { glfwTerminate(); } /****************************************************************************** * GLFW error callback ******************************************************************************/ void PtApplication::error_callback( int error, const char* description ) { fprintf( stderr, "Error: %s\n", description ); } /****************************************************************************** * Initialize windows ******************************************************************************/ void PtApplication::initializeWindows() { // Initialize windows mMainWindow->initializeWindow(); } /****************************************************************************** * Initialize GL library ******************************************************************************/ void PtApplication::initializeGL() { // NOTE: the following GLFW functions require a context to be current glfwMakeContextCurrent( mMainWindow->getWindow() ); // Load OpenGL API/extensions gladLoadGLLoader( (GLADloadproc)glfwGetProcAddress ); // Managing swap interval //glfwSwapInterval( 1 ); glfwSwapInterval( 0 ); // Initialize mMainWindow->initializeGL(); } /****************************************************************************** * Initialize ImGui user interface ******************************************************************************/ void PtApplication::initializeImGuiUserInterface() { // Need a GL context? glfwMakeContextCurrent( mMainWindow->getWindow() ); // Initialize ImGui // - GL binding //ImGui_ImplGlfwGL3_Init( mMainWindow->getWindow(), true ); // TODO: check callback: erased/overlapped by ImGui: use custom and call ImGui one !!! () => use FALSE !!!! // - style //ImGui::StyleColorsClassic(); //ImGui::StyleColorsDark(); } /****************************************************************************** * Execute * - main event loop ******************************************************************************/ void PtApplication::execute() { // Set context // NOTE: // By default, making a context non-current implicitly forces a pipeline flush // On machines that support GL_KHR_context_flush_control, you can control whether a context performs this flush by setting the GLFW_CONTEXT_RELEASE_BEHAVIOR window hint. glfwMakeContextCurrent( mMainWindow->getWindow() ); // Handle requests // - data model loading, descriptors computation, texture synthesis, painting, etc... handleRequests(); // Process events glfwPollEvents(); } /****************************************************************************** * Handle requests ******************************************************************************/ void PtApplication::handleRequests() { PtGraphics::PtGraphicsPPTBF* pptbfModel = getPPTBF(); pptbfModel->generatePPTBF( mBDDImageWidth, mBDDImageHeight, mPPTBFParameterFilename.c_str() ); } /****************************************************************************** * Post a request ******************************************************************************/ void PtApplication::postRequest( PtPipelineRequest pRequest ) { switch ( pRequest ) { case eLoadDataModel: mOmniScaleModelUpdateRequested = true; break; case eSynthesizeTexture: mTextureSynthesisRequested = true; break; default: break; } } /****************************************************************************** * Get PPTBF ******************************************************************************/ PtGraphicsPPTBF* PtApplication::getPPTBF() { return mMainWindow->getPPTBF(); } /****************************************************************************** * BDD image parameters ******************************************************************************/ void PtApplication::setBDDImageWidth( const int pValue ) { mBDDImageWidth = pValue; } /****************************************************************************** * BDD image parameters ******************************************************************************/ void PtApplication::setBDDImageHeight( const int pValue ) { mBDDImageHeight = pValue; } /****************************************************************************** * BDD image parameters ******************************************************************************/ void PtApplication::setBDDImageDirectory( const char* pPath ) { mBDDImageDirectory = pPath; } /****************************************************************************** * BDD serie ID ******************************************************************************/ void PtApplication::setBDDSerieID( const int pValue ) { mBDDserieID = pValue; } /****************************************************************************** * PPTBF parameters ******************************************************************************/ void PtApplication::setPPTBFParameterFilename( const char* pPath ) { mPPTBFParameterFilename = pPath; }
9,380
C++
.cpp
260
34.15
170
0.406615
ASTex-ICube/semiproctex
39
8
2
LGPL-2.1
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,917
main.cpp
ASTex-ICube_semiproctex/PPTBF_Structures_Src/Tools/PtBDDGenerator/main.cpp
/* * Publication: Semi-Procedural Textures Using Point Process Texture Basis Functions * Authors: anonymous * * Code author: Pascal Guehl * * anonymous * anonymous */ /** * @version 1.0 */ /****************************************************************************** ******************************* INCLUDE SECTION ****************************** ******************************************************************************/ // STL #include <iostream> #include <string> // System #include <cstdlib> #include <ctime> // Project #include "PtApplication.h" #include "PtGraphicsPPTBF.h" /****************************************************************************** ****************************** NAMESPACE SECTION ***************************** ******************************************************************************/ /****************************************************************************** ************************* DEFINE AND CONSTANT SECTION ************************ ******************************************************************************/ /****************************************************************************** ***************************** TYPE DEFINITION ******************************** ******************************************************************************/ /****************************************************************************** ***************************** METHOD DEFINITION ****************************** ******************************************************************************/ /****************************************************************************** * Main entry program * * @param pArgc Number of arguments * @param pArgv List of arguments * * @return flag telling whether or not it succeeds ******************************************************************************/ int main( int pArgc, char** pArgv ) { // LOG info std::cout << "-------------------------------------------------------------" << std::endl; std::cout << "- PPTBF Structures BDD Generator on GPU: Command Line Tool --" << std::endl; std::cout << "-------------------------------------------------------------" << std::endl; // Check command line arguments const int nbArguments = 3; if ( pArgc < ( 1 + nbArguments ) ) { std::cout << "ERROR: program requires 1 parameters..." << std::endl; std::cout << "\tprogram width height xxx_pptbf_params.txt" << std::endl; // Exit return -1; } // Retrieve program directory int indexParameter = 0; std::string workingDirectory = ""; workingDirectory = pArgv[ indexParameter++ ]; // User customizable parameters : retrieve command line parameters const int BDDImageWidth = std::stoi( pArgv[ indexParameter++ ] ); // default: 4 const int BDDImageHeight = std::stoi( pArgv[ indexParameter++ ] ); // default: 4 const char* pptbfParameterFilename = pArgv[ indexParameter++ ]; // default: "../imagestp/many_lichens_on_stone_6040019" std::cout << "\nPROCESSING: " << pptbfParameterFilename << std::endl; PtGUI::PtApplication& application = PtGUI::PtApplication::get(); // Initialization application.initialize( workingDirectory.c_str() ); // Set user parameters application.setBDDImageWidth( BDDImageWidth ); application.setBDDImageHeight( BDDImageHeight ); application.setPPTBFParameterFilename( pptbfParameterFilename ); PtGUI::PtApplication::get().execute(); // LOG info std::cout << "---------------------" << std::endl; std::cout << "- This is the end! --" << std::endl; std::cout << "---------------------" << std::endl; // Finalization application.finalize(); return 0; }
3,651
C++
.cpp
84
41.321429
120
0.430508
ASTex-ICube/semiproctex
39
8
2
LGPL-2.1
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,918
PtGraphicsPPTBF.cpp
ASTex-ICube_semiproctex/PPTBF_Structures_Src/PtGraphics/PtGraphicsPPTBF.cpp
/* * Publication: Semi-Procedural Textures Using Point Process Texture Basis Functions * Authors: anonymous * * Code author: Pascal Guehl * * anonymous * anonymous */ /** * @version 1.0 */ #include "PtGraphicsPPTBF.h" /****************************************************************************** ******************************* INCLUDE SECTION ****************************** ******************************************************************************/ // System #include <cassert> // STL #include <iostream> #include <algorithm> #include <functional> #include <numeric> #include <iomanip> #include <vector> #include <fstream> #include <cmath> // Project #include "PtNoise.h" #include "PtImageHelper.h" #include <PtEnvironment.h> /****************************************************************************** ****************************** NAMESPACE SECTION ***************************** ******************************************************************************/ // Project using namespace Pt; using namespace PtGraphics; /****************************************************************************** ************************* DEFINE AND CONSTANT SECTION ************************ ******************************************************************************/ //#define PROBE #define PRODUCT //#define WTRANSF //#define REFINEMENT /****************************************************************************** ***************************** TYPE DEFINITION ******************************** ******************************************************************************/ /****************************************************************************** ***************************** METHOD DEFINITION ****************************** ******************************************************************************/ /****************************************************************************** * Constructor ******************************************************************************/ PtGraphicsPPTBF::PtGraphicsPPTBF() : PtPPTBF() , mTexture_P( 0 ) , mTexture_rnd_tab( 0 ) , mTexture_G( 0 ) , mUseLowResolutionPPTBF( false ) , mWidthLowQuality( 512 ) , mHeightLowQuality( 512 ) , mTime( 0.f ) , mUpdateDeformation( true ) , mUpdatePointProcess( true ) , mUpdateWindowCellular( true ) , mUpdateFeature( true ) , mQueryTimeElapsed( 0 ) , mPPTBFGenerationTime( 0 ) , mSynthesisTime( 0.f ) , mSynthesisInfo() , mThreshold( 0.0f ) , mRenderingMode( ERenderingMode::ePPTBF ) , mThresholdTexture( 0 ) , mNbLabels( 0 ) , mPPTBFLabelMap( 0 ) , mPPTBFRandomValueMap( 0 ) { mShaderProgram = new PtShaderProgram(); mPPTBFViewerShaderProgram = new PtShaderProgram(); mBinaryStructureMapShaderProgram = new PtShaderProgram(); // PPTBF Megakernel approach mMegakernelShaderProgram = new PtShaderProgram(); // - with threshold mMegakernelThresholdShaderProgram = new PtShaderProgram(); } /****************************************************************************** * Destructor ******************************************************************************/ PtGraphicsPPTBF::~PtGraphicsPPTBF() { delete mShaderProgram; mShaderProgram = nullptr; delete mMegakernelShaderProgram; mMegakernelShaderProgram = nullptr; delete mMegakernelThresholdShaderProgram; mMegakernelThresholdShaderProgram = nullptr; delete mPPTBFViewerShaderProgram; mPPTBFViewerShaderProgram = nullptr; delete mBinaryStructureMapShaderProgram; mBinaryStructureMapShaderProgram = nullptr; } /****************************************************************************** * Initialize ******************************************************************************/ void PtGraphicsPPTBF::initialize( const int pWidth, const int pHeight ) { mWidth = pWidth; mHeight = pHeight; int width = pWidth; int height = pHeight; if ( mUseLowResolutionPPTBF ) { width = mWidthLowQuality; height = mHeightLowQuality; } // Initialize PRNG graphicsInitialization_PRNG(); // Initialize noise graphicsInitialization_Noise(); // Initialize timer(s) graphicsInitialization_Timer(); // Initialize shader programs bool statusOK = false; statusOK = initializeShaderPrograms(); assert( statusOK ); // Create device resources glGenFramebuffers( 1, &mPPTBFFrameBuffer ); glGenTextures( 1, &mPPTBFTexture ); // Initialize texture "rnd_tab" glBindTexture( GL_TEXTURE_2D, mPPTBFTexture ); // - set the texture wrapping/filtering options (on the currently bound texture object) glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); // - set min/max level for completeness glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0 ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0 ); // - generate the texture glTexImage2D( GL_TEXTURE_2D, 0, GL_R32F, width, height, 0/*border*/, GL_RED, GL_FLOAT, nullptr ); // - reset device state glBindTexture( GL_TEXTURE_2D, 0 ); // Configure framebuffer glBindFramebuffer( GL_FRAMEBUFFER, mPPTBFFrameBuffer ); glFramebufferTexture2D( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, mPPTBFTexture, 0 ); glDrawBuffer( GL_COLOR_ATTACHMENT0 ); // - check FBO status GLenum fboStatus = glCheckFramebufferStatus( GL_FRAMEBUFFER ); if ( fboStatus != GL_FRAMEBUFFER_COMPLETE ) { std::cout << "Framebuffer error - status: " << fboStatus << std::endl; // - clean device resources finalize(); // - reset device state glBindFramebuffer( GL_FRAMEBUFFER, 0 ); //return -1; } // - reset device state glBindFramebuffer( GL_FRAMEBUFFER, 0 ); //---------------------------------------------------- // Initialize label map glCreateTextures( GL_TEXTURE_2D, 1, &mPPTBFLabelMap ); glTextureParameteri( mPPTBFLabelMap, GL_TEXTURE_BASE_LEVEL, 0 ); glTextureParameteri( mPPTBFLabelMap, GL_TEXTURE_MAX_LEVEL, 0 ); // - allocate memory const GLsizei levels = 1; const GLenum internalFormat = GL_R8UI; glTextureStorage2D( mPPTBFLabelMap, levels, internalFormat, width, height ); // - fill data const GLenum format = GL_RED_INTEGER; const GLenum type = GL_UNSIGNED_BYTE; // 256 labels max //const void* data = getNoise()->getP().data(); //glTextureSubImage2D( mPPTBFLabelMap, 0/*level*/, 0/*xoffset*/, 0/*yoffset*/, width, height, format, type, data ); // - clear texture std::vector< char > nullData = { 0 }; glClearTexImage( mPPTBFLabelMap, /*level*/0, format, type, nullData.data() ); //---------------------------------------------------- //---------------------------------------------------- // Initialize label map { glCreateTextures( GL_TEXTURE_2D, 1, &mPPTBFRandomValueMap ); glTextureParameteri( mPPTBFRandomValueMap, GL_TEXTURE_BASE_LEVEL, 0 ); glTextureParameteri( mPPTBFRandomValueMap, GL_TEXTURE_MAX_LEVEL, 0 ); // - allocate memory const GLsizei levels = 1; const GLenum internalFormat = GL_R32F; glTextureStorage2D( mPPTBFRandomValueMap, levels, internalFormat, width, height ); // - fill data const GLenum format = GL_RED; const GLenum type = GL_FLOAT; //const void* data = getNoise()->getP().data(); //glTextureSubImage2D( mPPTBFRandomValueMap, 0/*level*/, 0/*xoffset*/, 0/*yoffset*/, width, height, format, type, data ); // - clear texture std::vector< float > nullData = { 0.f }; glClearTexImage( mPPTBFRandomValueMap, /*level*/0, format, type, nullData.data() ); } //---------------------------------------------------- // Binary structure map if ( mThresholdTexture ) { glDeleteTextures( 1, &mPPTBFTexture ); } graphicsInitialization_BinaryStructureMap(); } /****************************************************************************** * Initialize ******************************************************************************/ void PtGraphicsPPTBF::initialize( const int pWidth, const int pHeight, const int pNbOutputs ) { mWidth = pWidth; mHeight = pHeight; int width = pWidth; int height = pHeight; if ( mUseLowResolutionPPTBF ) { width = mWidthLowQuality; height = mHeightLowQuality; } // Initialize PRNG graphicsInitialization_PRNG(); // Initialize noise graphicsInitialization_Noise(); // Initialize timer(s) graphicsInitialization_Timer(); // Initialize shader programs bool statusOK = false; statusOK = initializeShaderPrograms(); assert( statusOK ); // Multiple outputs mPPTBFTextureLists.resize( pNbOutputs ); for ( auto& texture : mPPTBFTextureLists ) { // Create device resources glGenTextures( 1, &texture); // Initialize texture "rnd_tab" glBindTexture( GL_TEXTURE_2D, texture ); // - set the texture wrapping/filtering options (on the currently bound texture object) glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); // - set min/max level for completeness glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0 ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0 ); // - generate the texture glTexImage2D( GL_TEXTURE_2D, 0, GL_R32F, width, height, 0/*border*/, GL_RED, GL_FLOAT, nullptr ); } // - reset device state glBindTexture( GL_TEXTURE_2D, 0 ); //---------------------------------------------------- // Initialize label map glCreateTextures( GL_TEXTURE_2D, 1, &mPPTBFLabelMap ); glTextureParameteri( mPPTBFLabelMap, GL_TEXTURE_BASE_LEVEL, 0 ); glTextureParameteri( mPPTBFLabelMap, GL_TEXTURE_MAX_LEVEL, 0 ); // - allocate memory const GLsizei levels = 1; const GLenum internalFormat = GL_R8UI; glTextureStorage2D( mPPTBFLabelMap, levels, internalFormat, width, height ); // - fill data const GLenum format = GL_RED_INTEGER; const GLenum type = GL_UNSIGNED_BYTE; // 256 labels max //const void* data = getNoise()->getP().data(); //glTextureSubImage2D( mPPTBFLabelMap, 0/*level*/, 0/*xoffset*/, 0/*yoffset*/, width, height, format, type, data ); // - clear texture std::vector< char > nullData = { 0 }; glClearTexImage( mPPTBFLabelMap, /*level*/0, format, type, nullData.data() ); //---------------------------------------------------- //---------------------------------------------------- // Initialize label map { glCreateTextures( GL_TEXTURE_2D, 1, &mPPTBFRandomValueMap ); glTextureParameteri( mPPTBFRandomValueMap, GL_TEXTURE_BASE_LEVEL, 0 ); glTextureParameteri( mPPTBFRandomValueMap, GL_TEXTURE_MAX_LEVEL, 0 ); // - allocate memory const GLsizei levels = 1; const GLenum internalFormat = GL_R32F; glTextureStorage2D( mPPTBFRandomValueMap, levels, internalFormat, width, height ); // - fill data const GLenum format = GL_RED; const GLenum type = GL_FLOAT; //const void* data = getNoise()->getP().data(); //glTextureSubImage2D( mPPTBFRandomValueMap, 0/*level*/, 0/*xoffset*/, 0/*yoffset*/, width, height, format, type, data ); // - clear texture std::vector< float > nullData = { 0.f }; glClearTexImage( mPPTBFRandomValueMap, /*level*/0, format, type, nullData.data() ); } //---------------------------------------------------- // Binary structure map if ( mThresholdTexture ) { glDeleteTextures( 1, &mPPTBFTexture ); } graphicsInitialization_BinaryStructureMap(); } /****************************************************************************** * Initialize shader program ******************************************************************************/ bool PtGraphicsPPTBF::initializeShaderPrograms() { bool statusOK = false; // Global variables const std::string shaderPath = PtEnvironment::mShaderPath + std::string( "/" ); PtShaderProgram* shaderProgram = nullptr; PtShaderProgram::TShaderList shaders; std::string shaderFilename; std::vector< std::string > uniforms; // PPTBF // Initialize shader program // Initialize shader program shaderProgram = mShaderProgram; shaderProgram->finalize(); shaderProgram->initialize(); shaderProgram->setName( "exemplarPaletteViewer" ); shaderProgram->setInfo( "Exemplar Palette Viewer" ); // - path shaders.clear(); shaderFilename = shaderPath + "fullscreenTexturedTriangle_vert.glsl"; shaders.push_back( std::make_pair( PtShaderProgram::ShaderType::eVertexShader, shaderFilename ) ); shaderFilename = shaderPath + "fullscreenTexturedTriangle_color_frag.glsl"; shaders.push_back( std::make_pair( PtShaderProgram::ShaderType::eFragmentShader, shaderFilename ) ); statusOK = shaderProgram->initializeProgram( shaders ); // Store uniforms info (after shader program link() step) uniforms.clear(); uniforms.push_back( "uTexture" ); shaderProgram->registerUniforms( uniforms ); // Rendering: fullscreen triangle // Initialize shader program shaderProgram = mPPTBFViewerShaderProgram; shaderProgram->finalize(); shaderProgram->initialize(); shaderProgram->setName( "pptbfViewer" ); shaderProgram->setInfo( "PPTBF Viewer" ); // - path shaders.clear(); shaderFilename = shaderPath + "fullscreenTexturedTriangle_vert.glsl"; shaders.push_back( std::make_pair( PtShaderProgram::ShaderType::eVertexShader, shaderFilename ) ); shaderFilename = shaderPath + "fullscreenTexturedTriangle_frag.glsl"; shaders.push_back( std::make_pair( PtShaderProgram::ShaderType::eFragmentShader, shaderFilename ) ); statusOK = shaderProgram->initializeProgram( shaders ); // Store uniforms info (after shader program link() step) uniforms.clear(); uniforms.push_back( "uTexture" ); uniforms.push_back( "uSelected" ); shaderProgram->registerUniforms( uniforms ); // Binary structure map // Initialize shader program shaderProgram = mBinaryStructureMapShaderProgram; shaderProgram->finalize(); shaderProgram->initialize(); shaderProgram->setName( "binaryStructureMap" ); shaderProgram->setInfo( "Binary Structure Map" ); // - path shaders.clear(); shaderFilename = shaderPath + "fullscreenTexturedTriangle_vert.glsl"; shaders.push_back( std::make_pair( PtShaderProgram::ShaderType::eVertexShader, shaderFilename ) ); shaderFilename = shaderPath + "binaryStructureMap_frag.glsl"; shaders.push_back( std::make_pair( PtShaderProgram::ShaderType::eFragmentShader, shaderFilename ) ); statusOK = shaderProgram->initializeProgram( shaders ); // Store uniforms info (after shader program link() step) uniforms.clear(); uniforms.push_back( "uTexture" ); uniforms.push_back( "uThreshold" ); uniforms.push_back( "uMinValue" ); uniforms.push_back( "uMaxValue" ); uniforms.push_back( "uMeanValue" ); uniforms.push_back( "uSelected" ); shaderProgram->registerUniforms( uniforms ); // Megakernel approach // Initialize shader program shaderProgram = mMegakernelShaderProgram; shaderProgram->finalize(); shaderProgram->initialize(); shaderProgram->setName( "pptbfMegakernel" ); shaderProgram->setInfo( "PPTBF Megakernel" ); // - path shaders.clear(); shaderFilename = shaderPath + "pptbf_megakernel_v2_comp.glsl"; shaders.push_back( std::make_pair( PtShaderProgram::ShaderType::eComputeShader, shaderFilename ) ); statusOK = shaderProgram->initializeProgram( shaders ); // Store uniforms info (after shader program link() step) uniforms.clear(); // PPTBF parameters // - PRNG + Noise uniforms.push_back( "uPermutationTex" ); uniforms.push_back( "uNoiseTex" ); // - deformation uniforms.push_back( "uTurbulenceAmplitude_0" ); uniforms.push_back( "uTurbulenceAmplitude_1" ); uniforms.push_back( "uTurbulenceAmplitude_2" ); // - model transform uniforms.push_back( "uResolution" ); uniforms.push_back( "uShiftX" ); uniforms.push_back( "uShiftY" ); uniforms.push_back( "uRotation" ); uniforms.push_back( "uRescaleX" ); // - point process uniforms.push_back( "uPointProcessTilingType" ); uniforms.push_back( "uPointProcessJitter" ); // - window function uniforms.push_back( "uWindowShape" ); uniforms.push_back( "uWindowArity" ); uniforms.push_back( "uWindowLarp" ); uniforms.push_back( "uWindowNorm" ); uniforms.push_back( "uWindowSmooth" ); uniforms.push_back( "uWindowBlend" ); uniforms.push_back( "uWindowSigwcell" ); // - window function uniforms.push_back( "uFeatureBomb" ); uniforms.push_back( "uFeatureNorm" ); uniforms.push_back( "uFeatureWinfeatcorrel" ); uniforms.push_back( "uFeatureAniso" ); uniforms.push_back( "uFeatureNpmin" ); uniforms.push_back( "uFeatureNpmax" ); uniforms.push_back( "uFeatureSigcos" ); uniforms.push_back( "uFeatureSigcosvar" ); uniforms.push_back( "uFeatureFreq" ); uniforms.push_back( "uFeaturePhase" ); uniforms.push_back( "uFeatureThickness" ); uniforms.push_back( "uFeatureCourbure" ); uniforms.push_back( "uFeatureDeltaorient" ); // - window function uniforms.push_back( "uThreshold" ); // - labeling uniforms.push_back( "uNbLabels" ); // - register uniforms shaderProgram->registerUniforms( uniforms ); // Megakernel approach with threshold // Initialize shader program shaderProgram = mMegakernelThresholdShaderProgram; shaderProgram->finalize(); shaderProgram->initialize(); shaderProgram->setName( "pptbfMegakernelThreshold" ); shaderProgram->setInfo( "PPTBF Megakernel Threshold" ); // - path shaders.clear(); shaderFilename = shaderPath + "pptbf_megakernel_threshold_v2_comp.glsl"; shaders.push_back( std::make_pair( PtShaderProgram::ShaderType::eComputeShader, shaderFilename ) ); statusOK = shaderProgram->initializeProgram( shaders ); // Store uniforms info (after shader program link() step) uniforms.clear(); // PPTBF parameters // - binary structure map uniforms.push_back( "uThreshold" ); // - register uniforms shaderProgram->registerUniforms( uniforms ); return statusOK; } /****************************************************************************** * Callback called when PPTBF size has been modified ******************************************************************************/ void PtGraphicsPPTBF::onSizeModified( const int pWidth, const int pHeight ) { // Release graphics resources if ( mPPTBFFrameBuffer ) { glDeleteFramebuffers( 1, &mPPTBFFrameBuffer ); } if ( mPPTBFTexture ) { glDeleteTextures( 1, &mPPTBFTexture ); } // PPTBF label map if ( mPPTBFLabelMap ) { glDeleteTextures( 1, &mPPTBFLabelMap ); } // Random value map if ( mPPTBFRandomValueMap ) { glDeleteTextures( 1, &mPPTBFRandomValueMap ); } mWidth = pWidth; mHeight = pHeight; int width = pWidth; int height = pHeight; if ( mUseLowResolutionPPTBF ) { width = mWidthLowQuality; height = mHeightLowQuality; } // Create device resources glGenFramebuffers( 1, &mPPTBFFrameBuffer ); glGenTextures( 1, &mPPTBFTexture ); // Initialize texture "rnd_tab" glBindTexture( GL_TEXTURE_2D, mPPTBFTexture ); // - set the texture wrapping/filtering options (on the currently bound texture object) glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); // - set min/max level for completeness glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0 ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0 ); // - generate the texture glTexImage2D( GL_TEXTURE_2D, 0, GL_R32F, width, height, 0/*border*/, GL_RED, GL_FLOAT, nullptr ); // - reset device state glBindTexture( GL_TEXTURE_2D, 0 ); // Configure framebuffer glBindFramebuffer( GL_FRAMEBUFFER, mPPTBFFrameBuffer ); glFramebufferTexture2D( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, mPPTBFTexture, 0 ); glDrawBuffer( GL_COLOR_ATTACHMENT0 ); // - check FBO status GLenum fboStatus = glCheckFramebufferStatus( GL_FRAMEBUFFER ); if ( fboStatus != GL_FRAMEBUFFER_COMPLETE ) { std::cout << "Framebuffer error - status: " << fboStatus << std::endl; // - clean device resources finalize(); // - reset device state glBindFramebuffer( GL_FRAMEBUFFER, 0 ); //return -1; } // - reset device state glBindFramebuffer( GL_FRAMEBUFFER, 0 ); //---------------------------------------------------- // Initialize label map glCreateTextures( GL_TEXTURE_2D, 1, &mPPTBFLabelMap ); glTextureParameteri( mPPTBFLabelMap, GL_TEXTURE_BASE_LEVEL, 0 ); glTextureParameteri( mPPTBFLabelMap, GL_TEXTURE_MAX_LEVEL, 0 ); // - allocate memory const GLsizei levels = 1; const GLenum internalFormat = GL_R8UI; glTextureStorage2D( mPPTBFLabelMap, levels, internalFormat, width, height ); // - fill data const GLenum format = GL_RED_INTEGER; const GLenum type = GL_UNSIGNED_BYTE; // 256 labels max //const void* data = getNoise()->getP().data(); //glTextureSubImage2D( mPPTBFLabelMap, 0/*level*/, 0/*xoffset*/, 0/*yoffset*/, width, height, format, type, data ); // - clear texture std::vector< char > nullData = { 0 }; glClearTexImage( mPPTBFLabelMap, /*level*/0, format, type, nullData.data() ); //---------------------------------------------------- //---------------------------------------------------- // Initialize random value map { glCreateTextures( GL_TEXTURE_2D, 1, &mPPTBFRandomValueMap ); glTextureParameteri( mPPTBFRandomValueMap, GL_TEXTURE_BASE_LEVEL, 0 ); glTextureParameteri( mPPTBFRandomValueMap, GL_TEXTURE_MAX_LEVEL, 0 ); // - allocate memory const GLsizei levels = 1; const GLenum internalFormat = GL_R32F; glTextureStorage2D( mPPTBFRandomValueMap, levels, internalFormat, width, height ); // - fill data const GLenum format = GL_RED; const GLenum type = GL_FLOAT; //const void* data = getNoise()->getP().data(); //glTextureSubImage2D( mPPTBFRandomValueMap, 0/*level*/, 0/*xoffset*/, 0/*yoffset*/, width, height, format, type, data ); // - clear texture std::vector< float > nullData = { 0.f }; glClearTexImage( mPPTBFRandomValueMap, /*level*/0, format, type, nullData.data() ); } //---------------------------------------------------- // Binary structure map if ( mThresholdTexture ) { glDeleteTextures( 1, &mThresholdTexture ); } graphicsInitialization_BinaryStructureMap(); } /****************************************************************************** * Finalize ******************************************************************************/ void PtGraphicsPPTBF::finalize() { if ( mTexture_P ) { glDeleteTextures( 1, &mTexture_P ); } if ( mTexture_rnd_tab ) { glDeleteTextures( 1, &mTexture_rnd_tab ); } if ( mTexture_G ) { glDeleteTextures( 1, &mTexture_G ); } // Finalize timer(s) graphicsFinalization_Timer(); } /****************************************************************************** * Initialize binary structure map ******************************************************************************/ void PtGraphicsPPTBF::graphicsInitialization_BinaryStructureMap() { // Retrieve PPTBF info const int width = getWidth(); const int height = getHeight(); assert( width != 0 && height != 0 ); // Common GL parameters const GLint param_TEXTURE_WRAP_S = GL_CLAMP_TO_EDGE; /*GL_REPEAT*/ const GLint param_TEXTURE_WRAP_T = GL_CLAMP_TO_EDGE; /*GL_REPEAT*/ const GLint param_TEXTURE_MIN_FILTER = GL_NEAREST; /*GL_LINEAR*/ const GLint param_TEXTURE_MAG_FILTER = GL_NEAREST; /*GL_LINEAR*/ GLuint& texture = mThresholdTexture; glCreateTextures( GL_TEXTURE_2D, 1, &texture ); // - set texture wrapping/filtering options glTextureParameteri( texture, GL_TEXTURE_WRAP_S, param_TEXTURE_WRAP_S ); glTextureParameteri( texture, GL_TEXTURE_WRAP_T, param_TEXTURE_WRAP_T ); glTextureParameteri( texture, GL_TEXTURE_MIN_FILTER, param_TEXTURE_MIN_FILTER ); glTextureParameteri( texture, GL_TEXTURE_MAG_FILTER, param_TEXTURE_MAG_FILTER ); // - set min/max level for completeness glTextureParameteri( texture, GL_TEXTURE_BASE_LEVEL, 0 ); glTextureParameteri( texture, GL_TEXTURE_MAX_LEVEL, 0 ); // - allocate memory glTextureStorage2D( texture, 1/*levels*/, GL_R32F, width, height ); // - clear texture float nullData = 0.f; glClearTexImage( texture, 0, GL_RED, GL_FLOAT, &nullData ); } /****************************************************************************** * Load a texture * * @param pFilename image ******************************************************************************/ bool PtGraphicsPPTBF::loadTexture( const char* pFilename, const int pNbRequestedChannels, const GLenum pInternalFormat, const GLenum pFormat, const GLenum pType, const bool pGenerateMipmap, GLuint& pTexture, int& pWidth, int& pHeight ) { // Open file std::ifstream file; file.open( pFilename ); if ( ! file.is_open() ) { std::cout << "ERROR: file cannot be opened: " << std::string( pFilename ) << std::endl; assert( false ); return false; } // Load image int width, height, nrChannels; const std::string imageFilename = pFilename; unsigned char* data = nullptr; const int desired_channels = pNbRequestedChannels; // force that many components per pixel PtImageHelper::loadImage( imageFilename.c_str(), width, height, nrChannels, data, desired_channels ); if ( data == nullptr ) { std::cout << "Failed to load image: " << imageFilename << std::endl; assert( false ); return false; } // Store txeture info pWidth = width; pHeight = height; // Compute the number of mipmap levels corresponding to given width and height of an image const int nbMipmapLevels = getNbMipmapLevels( width, height ); // Release graphics resources glDeleteTextures( 1, &pTexture ); // Initialize texture glCreateTextures( GL_TEXTURE_2D, 1, &pTexture ); // - set the texture wrapping/filtering options (on the currently bound texture object) glTextureParameteri( pTexture, GL_TEXTURE_WRAP_S, /*GL_REPEAT*/GL_CLAMP_TO_EDGE ); glTextureParameteri( pTexture, GL_TEXTURE_WRAP_T, /*GL_REPEAT*/GL_CLAMP_TO_EDGE ); glTextureParameteri( pTexture, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR ); glTextureParameteri( pTexture, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); // - set min/max level for completeness glTextureParameteri( pTexture, GL_TEXTURE_BASE_LEVEL, 0 ); GLint textureMaxLevel = 0; if ( pGenerateMipmap ) { textureMaxLevel = nbMipmapLevels - 1; } glTextureParameteri( pTexture, GL_TEXTURE_MAX_LEVEL, textureMaxLevel ); #if 1 // - deal with odd texture dimensions glBindTexture( GL_TEXTURE_2D, pTexture ); glPixelStorei( GL_UNPACK_ALIGNMENT, 1 ); glPixelStorei( GL_UNPACK_ROW_LENGTH, 0 ); glPixelStorei( GL_UNPACK_SKIP_PIXELS, 0 ); glPixelStorei( GL_UNPACK_SKIP_ROWS, 0 ); #endif // - allocate memory GLsizei levels = 1; if ( pGenerateMipmap ) { levels = nbMipmapLevels; } glTextureStorage2D( pTexture, levels, pInternalFormat, width, height ); // - fill data glTextureSubImage2D( pTexture, 0/*level*/, 0/*xoffset*/, 0/*yoffset*/, width, height, pFormat, pType, data ); // Mipmap generation if ( pGenerateMipmap ) { glGenerateTextureMipmap( pTexture ); } // - object name const std::string objectLabel = "PtGraphicsSynthesizer::exemplar"; glObjectLabel( GL_TEXTURE, pTexture, sizeof( objectLabel ), objectLabel.data() ); // Free memory PtImageHelper::freeImage( data ); return true; } /****************************************************************************** * Initialize PRNG (permutation texture) ******************************************************************************/ void PtGraphicsPPTBF::graphicsInitialization_PRNG() { // Initialize texture GLuint& texture = mTexture_P; glCreateTextures( GL_TEXTURE_2D, 1, &texture ); // - set the texture wrapping/filtering options (on the currently bound texture object) glTextureParameteri( texture, GL_TEXTURE_WRAP_S, GL_REPEAT/*GL_CLAMP_TO_EDGE*/ ); glTextureParameteri( texture, GL_TEXTURE_WRAP_T, GL_REPEAT/*GL_CLAMP_TO_EDGE*/ ); glTextureParameteri( texture, GL_TEXTURE_MIN_FILTER, GL_NEAREST ); glTextureParameteri( texture, GL_TEXTURE_MAG_FILTER, GL_NEAREST ); // - set min/max level for completeness glTextureParameteri( texture, GL_TEXTURE_BASE_LEVEL, 0 ); glTextureParameteri( texture, GL_TEXTURE_MAX_LEVEL, 0 ); #if 0 // - deal with odd texture dimensions glBindTexture( GL_TEXTURE_2D, texture ); glPixelStorei( GL_UNPACK_ALIGNMENT, 1 ); glPixelStorei( GL_UNPACK_ROW_LENGTH, 0 ); glPixelStorei( GL_UNPACK_SKIP_PIXELS, 0 ); glPixelStorei( GL_UNPACK_SKIP_ROWS, 0 ); #endif // - allocate memory const GLsizei levels = 1; const GLenum internalFormat = GL_R32I; const GLsizei width = static_cast< GLsizei >( getNoise()->getP().size() ); const GLsizei height = 1; glTextureStorage2D( texture, levels, internalFormat, width, height ); // - fill data const GLenum format = GL_RED_INTEGER; const GLenum type = GL_INT; const void* data = getNoise()->getP().data(); glTextureSubImage2D( texture, 0/*level*/, 0/*xoffset*/, 0/*yoffset*/, width, height, format, type, data ); } /****************************************************************************** * Initialize noise ******************************************************************************/ void PtGraphicsPPTBF::graphicsInitialization_Noise() { // Initialize sampler GLuint& sampler = mSampler_PRNG_Noise; glCreateSamplers( 1, &sampler ); // - set the sampler wrapping/filtering options glSamplerParameteri( sampler, GL_TEXTURE_WRAP_S, GL_REPEAT/*GL_CLAMP_TO_EDGE*/ ); glSamplerParameteri( sampler, GL_TEXTURE_WRAP_T, GL_REPEAT/*GL_CLAMP_TO_EDGE*/ ); glSamplerParameteri( sampler, GL_TEXTURE_MIN_FILTER, GL_NEAREST ); glSamplerParameteri( sampler, GL_TEXTURE_MAG_FILTER, GL_NEAREST ); // Initialize texture "rnd_tab" graphicsInitialization_Noise_rnd_tab(); // Initialize texture "G" graphicsInitialization_Noise_G(); } /****************************************************************************** * Initialize noise ******************************************************************************/ void PtGraphicsPPTBF::graphicsInitialization_Noise_rnd_tab() { // Initialize texture "rnd_tab" GLuint& texture = mTexture_rnd_tab; glCreateTextures( GL_TEXTURE_2D, 1, &texture ); // - set min/max level for completeness glTextureParameteri( texture, GL_TEXTURE_BASE_LEVEL, 0 ); glTextureParameteri( texture, GL_TEXTURE_MAX_LEVEL, 0 ); #if 0 // - deal with odd texture dimensions glBindTexture( GL_TEXTURE_2D, texture ); glPixelStorei( GL_UNPACK_ALIGNMENT, 1 ); glPixelStorei( GL_UNPACK_ROW_LENGTH, 0 ); glPixelStorei( GL_UNPACK_SKIP_PIXELS, 0 ); glPixelStorei( GL_UNPACK_SKIP_ROWS, 0 ); #endif // - allocate memory const GLsizei levels = 1; const GLenum internalFormat = GL_R32F; const GLsizei width = static_cast< GLsizei >( getNoise()->getRndTab().size() ); const GLsizei height = 1; glTextureStorage2D( texture, levels, internalFormat, width, height ); // - fill data const GLenum format = GL_RED; const GLenum type = GL_FLOAT; const void* data = getNoise()->getRndTab().data(); glTextureSubImage2D( texture, 0/*level*/, 0/*xoffset*/, 0/*yoffset*/, width, height, format, type, data ); } /****************************************************************************** * Initialize noise ******************************************************************************/ void PtGraphicsPPTBF::graphicsInitialization_Noise_G() { // Initialize texture "G" GLuint& texture = mTexture_G; glCreateTextures( GL_TEXTURE_2D, 1, &texture ); // - set min/max level for completeness glTextureParameteri( texture, GL_TEXTURE_BASE_LEVEL, 0 ); glTextureParameteri( texture, GL_TEXTURE_MAX_LEVEL, 0 ); #if 0 // - deal with odd texture dimensions glBindTexture( GL_TEXTURE_2D, texture ); glPixelStorei( GL_UNPACK_ALIGNMENT, 1 ); glPixelStorei( GL_UNPACK_ROW_LENGTH, 0 ); glPixelStorei( GL_UNPACK_SKIP_PIXELS, 0 ); glPixelStorei( GL_UNPACK_SKIP_ROWS, 0 ); #endif // - allocate memory const GLsizei levels = 1; const GLenum internalFormat = GL_RGB32F; const GLsizei width = static_cast< GLsizei >( getNoise()->getG().size() ); const GLsizei height = 1; glTextureStorage2D( texture, levels, internalFormat, width, height ); // - fill data const GLenum format = GL_RGB; const GLenum type = GL_FLOAT; const void* data = getNoise()->getG().data(); glTextureSubImage2D( texture, 0/*level*/, 0/*xoffset*/, 0/*yoffset*/, width, height, format, type, data ); } /****************************************************************************** * Initialize timer(s) ******************************************************************************/ void PtGraphicsPPTBF::graphicsInitialization_Timer() { // Device timer glCreateQueries( GL_TIME_ELAPSED, 1, &mQueryTimeElapsed ); } /****************************************************************************** * Finalize timer(s) ******************************************************************************/ void PtGraphicsPPTBF::graphicsFinalization_Timer() { // Device timer glDeleteQueries( 1, &mQueryTimeElapsed ); } /****************************************************************************** * Launch PPTBF computation ******************************************************************************/ void PtGraphicsPPTBF::compute() { static int counter = 0; std::cout << "synthesis: " << counter << std::endl; counter++; // GPU timer GLuint64 result = 0; GLuint64 totalTime = 0; mSynthesisInfo = std::stringstream(); // NOTE: don't use clear() => it is not what you may think... // Timer glBeginQuery( GL_TIME_ELAPSED, mQueryTimeElapsed ); // Execute the mega-kernel approach executeMegakernelApproach(); // Timer glEndQuery( GL_TIME_ELAPSED ); glGetQueryObjectui64v( mQueryTimeElapsed, GL_QUERY_RESULT, &result ); totalTime += result; // LOG info mSynthesisInfo << " Mega-Kernel "; mSynthesisInfo << "\t" << std::fixed << std::setw( 9 ) << std::setprecision( 3 ) << std::setfill( ' ' ) << ( ( totalTime ) * 1.e-6 ) << " ms\n"; // Update internal performance counter mSynthesisTime = static_cast< float >( totalTime * 1.e-6 ); // LOG info std::cout << "\tTOTAL: "; std::cout << "\t" << std::fixed << std::setw( 9 ) << std::setprecision( 3 ) << std::setfill( ' ' ) << ( totalTime * 1.e-6 ) << " ms\n"; } /****************************************************************************** * Launch PPTBF computation ******************************************************************************/ void PtGraphicsPPTBF::compute( const int pOutputID ) { static int counter = 0; std::cout << "synthesis: " << counter << std::endl; counter++; // GPU timer GLuint64 result = 0; GLuint64 totalTime = 0; mSynthesisInfo = std::stringstream(); // NOTE: don't use clear() => it is not what you may think... // Timer glBeginQuery( GL_TIME_ELAPSED, mQueryTimeElapsed ); // Execute the mega-kernel approach executeMegakernelApproach( pOutputID ); // Timer glEndQuery( GL_TIME_ELAPSED ); glGetQueryObjectui64v( mQueryTimeElapsed, GL_QUERY_RESULT, &result ); totalTime += result; // LOG info mSynthesisInfo << " Mega-Kernel "; mSynthesisInfo << "\t" << std::fixed << std::setw( 9 ) << std::setprecision( 3 ) << std::setfill( ' ' ) << ( ( totalTime ) * 1.e-6 ) << " ms\n"; // Update internal performance counter mSynthesisTime = static_cast< float >( totalTime * 1.e-6 ); // LOG info std::cout << "\tTOTAL: "; std::cout << "\t" << std::fixed << std::setw( 9 ) << std::setprecision( 3 ) << std::setfill( ' ' ) << ( totalTime * 1.e-6 ) << " ms\n"; } /****************************************************************************** * Execute the mega-kernel approach ******************************************************************************/ void PtGraphicsPPTBF::executeMegakernelApproach() { // Compute PPTBF // Megakernel approach // Set shader program //PtShaderProgram* shaderProgram = editPPTBFGeneratorShaderProgram(); PtShaderProgram* shaderProgram = nullptr; /*switch ( mRenderingMode ) { case ERenderingMode::ePPTBF: shaderProgram = mMegakernelShaderProgram; break; case ERenderingMode::eBinaryMap: shaderProgram = mMegakernelThresholdShaderProgram; break; default: shaderProgram = mMegakernelShaderProgram; break; }*/ shaderProgram = mMegakernelShaderProgram; shaderProgram->use(); { // Set texture(s) #if 1 glBindTextureUnit( 0/*unit*/, mTexture_P ); glBindTextureUnit( 1/*unit*/, mTexture_rnd_tab ); #else GLuint textures[ 3 ] = { mTexture_P , mTexture_G, mTexture_rnd_tab }; glBindTextures( 0/*first*/, 3/*count*/, textures ); #endif // Set sampler(s) #if 1 glBindSampler( 0/*unit*/, mSampler_PRNG_Noise ); glBindSampler( 1/*unit*/, mSampler_PRNG_Noise ); #else std::vector< GLuint > samplers( 3, mSampler_PRNG_Noise ); glBindSamplers( 0/*first*/, 3/*count*/, samplers.data() ); #endif // Set image(s) // - PPTBF (output) glBindImageTexture( 0/*unit*/, mPPTBFTexture, 0/*level*/, GL_FALSE/*layered*/, 0/*layer*/, GL_WRITE_ONLY, GL_R32F ); // - labeling glBindImageTexture( 1/*unit*/, mPPTBFLabelMap, 0/*level*/, GL_FALSE/*layered*/, 0/*layer*/, GL_WRITE_ONLY, GL_R8UI ); // - labeling glBindImageTexture( 2/*unit*/, mPPTBFRandomValueMap, 0/*level*/, GL_FALSE/*layered*/, 0/*layer*/, GL_WRITE_ONLY, GL_R32F ); // Set uniform(s) // - PRNG shaderProgram->set( 0, "uPermutationTex" ); // - noise shaderProgram->set( 1, "uNoiseTex" ); // - deformation shaderProgram->set( getTurbulenceAmplitude0(), "uTurbulenceAmplitude_0" ); shaderProgram->set( getTurbulenceAmplitude1(), "uTurbulenceAmplitude_1" ); shaderProgram->set( getTurbulenceAmplitude2(), "uTurbulenceAmplitude_2" ); // - model transform shaderProgram->set( getResolution(), "uResolution" ); shaderProgram->set( getAlpha(), "uRotation" ); shaderProgram->set( getRescalex(), "uRescaleX" ); shaderProgram->set( getShiftX(), "uShiftX" ); shaderProgram->set( getShiftY(), "uShiftY" ); // - point process shaderProgram->set( getTilingType(), "uPointProcessTilingType" ); shaderProgram->set( getJittering(), "uPointProcessJitter" ); // - window function shaderProgram->set( getWindowShape(), "uWindowShape" ); shaderProgram->set( getWindowArity(), "uWindowArity" ); shaderProgram->set( getWindowLarp(), "uWindowLarp" ); shaderProgram->set( getWindowNorm(), "uWindowNorm" ); shaderProgram->set( getWindowSmooth(), "uWindowSmooth" ); shaderProgram->set( getWindowBlend(), "uWindowBlend" ); shaderProgram->set( getWindowSigwcell(), "uWindowSigwcell" ); // - feature function shaderProgram->set( getBombingFlag(), "uFeatureBomb" ); shaderProgram->set( getFeatureNorm(), "uFeatureNorm" ); shaderProgram->set( getFeatureWinfeatcorrel(), "uFeatureWinfeatcorrel" ); shaderProgram->set( getFeatureAnisotropy(), "uFeatureAniso" ); shaderProgram->set( getMinNbGaborKernels(), "uFeatureNpmin" ); shaderProgram->set( getMaxNbGaborKernels(), "uFeatureNpmax" ); shaderProgram->set( getGaborDecay(), "uFeatureSigcos" ); shaderProgram->set( getGaborDecayJittering(), "uFeatureSigcosvar" ); shaderProgram->set( getGaborStripesFrequency(), "uFeatureFreq" ); shaderProgram->set( getFeaturePhaseShift(), "uFeaturePhase" ); shaderProgram->set( getGaborStripesThickness(), "uFeatureThickness" ); shaderProgram->set( getGaborStripesCurvature(), "uFeatureCourbure" ); shaderProgram->set( getGaborStripesOrientation(), "uFeatureDeltaorient" ); // - labeling shaderProgram->set( getNbLabels(), "uNbLabels" ); // Launch kernel // - block const int blockSizeX = 8; // TODO: benchmark with 8x8, 16x16 and 32x32 const int blockSizeY = 8; // - grid const int width = getWidth(); const int height = getHeight(); assert(width != 0 && height != 0); const GLuint gridSizeX = glm::max( ( width + blockSizeX - 1 ) / blockSizeX, 1 ); const GLuint gridSizeY = glm::max( ( height + blockSizeY - 1 ) / blockSizeY, 1 ); // - kernel glDispatchCompute( gridSizeX, gridSizeY, 1 ); // Reset GL state(s) //glBindTexture( GL_TEXTURE_2D, 0 ); } PtShaderProgram::unuse(); // Synchronization // - make sure writing to image has finished before read glMemoryBarrier( GL_SHADER_IMAGE_ACCESS_BARRIER_BIT ); // pb: wait for nothing? use a boolean if someone need to sample texture glMemoryBarrier( GL_ALL_BARRIER_BITS ); } /****************************************************************************** * Execute the mega-kernel approach ******************************************************************************/ void PtGraphicsPPTBF::executeMegakernelApproach( const int pOutputID ) { // Compute PPTBF // Megakernel approach // Set shader program //PtShaderProgram* shaderProgram = editPPTBFGeneratorShaderProgram(); PtShaderProgram* shaderProgram = nullptr; /*switch ( mRenderingMode ) { case ERenderingMode::ePPTBF: shaderProgram = mMegakernelShaderProgram; break; case ERenderingMode::eBinaryMap: shaderProgram = mMegakernelThresholdShaderProgram; break; default: shaderProgram = mMegakernelShaderProgram; break; }*/ shaderProgram = mMegakernelShaderProgram; shaderProgram->use(); { // Set texture(s) #if 1 glBindTextureUnit( 0/*unit*/, mTexture_P ); glBindTextureUnit( 1/*unit*/, mTexture_rnd_tab ); #else GLuint textures[ 3 ] = { mTexture_P , mTexture_G, mTexture_rnd_tab }; glBindTextures( 0/*first*/, 3/*count*/, textures ); #endif // Set sampler(s) #if 1 glBindSampler( 0/*unit*/, mSampler_PRNG_Noise ); glBindSampler( 1/*unit*/, mSampler_PRNG_Noise ); #else std::vector< GLuint > samplers( 3, mSampler_PRNG_Noise ); glBindSamplers( 0/*first*/, 3/*count*/, samplers.data() ); #endif // Set image(s) // - PPTBF (output) //glBindImageTexture( 0/*unit*/, mPPTBFTexture, 0/*level*/, GL_FALSE/*layered*/, 0/*layer*/, GL_WRITE_ONLY, GL_R32F ); glBindImageTexture( 0/*unit*/, mPPTBFTextureLists[ pOutputID ], 0/*level*/, GL_FALSE/*layered*/, 0/*layer*/, GL_WRITE_ONLY, GL_R32F ); // - labeling glBindImageTexture( 1/*unit*/, mPPTBFLabelMap, 0/*level*/, GL_FALSE/*layered*/, 0/*layer*/, GL_WRITE_ONLY, GL_R8UI ); // - labeling glBindImageTexture( 2/*unit*/, mPPTBFRandomValueMap, 0/*level*/, GL_FALSE/*layered*/, 0/*layer*/, GL_WRITE_ONLY, GL_R32F ); // Set uniform(s) // - PRNG shaderProgram->set( 0, "uPermutationTex" ); // - noise shaderProgram->set( 1, "uNoiseTex" ); // - deformation shaderProgram->set( getTurbulenceAmplitude0(), "uTurbulenceAmplitude_0" ); shaderProgram->set( getTurbulenceAmplitude1(), "uTurbulenceAmplitude_1" ); shaderProgram->set( getTurbulenceAmplitude2(), "uTurbulenceAmplitude_2" ); // - model transform shaderProgram->set( getResolution(), "uResolution" ); shaderProgram->set( getAlpha(), "uRotation" ); shaderProgram->set( getRescalex(), "uRescaleX" ); shaderProgram->set( getShiftX(), "uShiftX" ); shaderProgram->set( getShiftY(), "uShiftY" ); // - point process shaderProgram->set( getTilingType(), "uPointProcessTilingType" ); shaderProgram->set( getJittering(), "uPointProcessJitter" ); // - window function shaderProgram->set( getWindowShape(), "uWindowShape" ); shaderProgram->set( getWindowArity(), "uWindowArity" ); shaderProgram->set( getWindowLarp(), "uWindowLarp" ); shaderProgram->set( getWindowNorm(), "uWindowNorm" ); shaderProgram->set( getWindowSmooth(), "uWindowSmooth" ); shaderProgram->set( getWindowBlend(), "uWindowBlend" ); shaderProgram->set( getWindowSigwcell(), "uWindowSigwcell" ); // - feature function shaderProgram->set( getBombingFlag(), "uFeatureBomb" ); shaderProgram->set( getFeatureNorm(), "uFeatureNorm" ); shaderProgram->set( getFeatureWinfeatcorrel(), "uFeatureWinfeatcorrel" ); shaderProgram->set( getFeatureAnisotropy(), "uFeatureAniso" ); shaderProgram->set( getMinNbGaborKernels(), "uFeatureNpmin" ); shaderProgram->set( getMaxNbGaborKernels(), "uFeatureNpmax" ); shaderProgram->set( getGaborDecay(), "uFeatureSigcos" ); shaderProgram->set( getGaborDecayJittering(), "uFeatureSigcosvar" ); shaderProgram->set( getGaborStripesFrequency(), "uFeatureFreq" ); shaderProgram->set( getFeaturePhaseShift(), "uFeaturePhase" ); shaderProgram->set( getGaborStripesThickness(), "uFeatureThickness" ); shaderProgram->set( getGaborStripesCurvature(), "uFeatureCourbure" ); shaderProgram->set( getGaborStripesOrientation(), "uFeatureDeltaorient" ); // - labeling shaderProgram->set( getNbLabels(), "uNbLabels" ); // Launch kernel // - block const int blockSizeX = 8; // TODO: benchmark with 8x8, 16x16 and 32x32 const int blockSizeY = 8; // - grid const int width = getWidth(); const int height = getHeight(); assert(width != 0 && height != 0); const GLuint gridSizeX = glm::max( ( width + blockSizeX - 1 ) / blockSizeX, 1 ); const GLuint gridSizeY = glm::max( ( height + blockSizeY - 1 ) / blockSizeY, 1 ); // - kernel glDispatchCompute( gridSizeX, gridSizeY, 1 ); // Reset GL state(s) //glBindTexture( GL_TEXTURE_2D, 0 ); } PtShaderProgram::unuse(); // Synchronization // - make sure writing to image has finished before read glMemoryBarrier( GL_SHADER_IMAGE_ACCESS_BARRIER_BIT ); // pb: wait for nothing? use a boolean if someone need to sample texture glMemoryBarrier( GL_ALL_BARRIER_BITS ); } /****************************************************************************** * Compute binary structure map ******************************************************************************/ void PtGraphicsPPTBF::computeBinaryStructureMap() { PtShaderProgram* shaderProgram = mMegakernelThresholdShaderProgram; shaderProgram->use(); { // Set image(s) // - PPTBF (output) glBindImageTexture( 0/*unit*/, mThresholdTexture, 0/*level*/, GL_FALSE/*layered*/, 0/*layer*/, GL_WRITE_ONLY, GL_R32F ); // - binary structure map glBindImageTexture( 1/*unit*/, mPPTBFTexture, 0/*level*/, GL_FALSE/*layered*/, 0/*layer*/, GL_READ_ONLY, GL_R32F ); // Set uniform(s) // - threshold shaderProgram->set( getThreshold(), "uThreshold" ); // Launch kernel // - block const int blockSizeX = 8; // TODO: benchmark with 8x8, 16x16 and 32x32 const int blockSizeY = 8; // - grid const int width = getWidth(); const int height = getHeight(); assert(width != 0 && height != 0); const GLuint gridSizeX = glm::max( ( width + blockSizeX - 1 ) / blockSizeX, 1 ); const GLuint gridSizeY = glm::max( ( height + blockSizeY - 1 ) / blockSizeY, 1 ); // - kernel glDispatchCompute( gridSizeX, gridSizeY, 1 ); // Reset GL state(s) //glBindTexture( GL_TEXTURE_2D, 0 ); } PtShaderProgram::unuse(); // Synchronization // - make sure writing to image has finished before read glMemoryBarrier( GL_SHADER_IMAGE_ACCESS_BARRIER_BIT ); // pb: wait for nothing? use a boolean if someone need to sample texture glMemoryBarrier( GL_ALL_BARRIER_BITS ); } /****************************************************************************** * Render PPTBF ******************************************************************************/ void PtGraphicsPPTBF::render() { if ( mRenderingMode == ERenderingMode::ePPTBF ) { } #if 0 // Set shader program PtShaderProgram* shaderProgram = mPPTBFViewerShaderProgram; shaderProgram->use(); { // Set texture(s) //glBindTextureUnit( 0/*unit*/, mPPTBFTexture ); // TEST: display separable pass // - window function //const GLuint* const windowCellularTextureID = mWindowCellular->getTextureID(); //glBindTextureUnit( 0/*unit*/, *windowCellularTextureID ); //// - feature function //const GLuint* const featureTextureID = mFeatureManager->getTextureID(); //glBindTextureUnit( 0/*unit*/, *featureTextureID ); // - PPTBF (compositing) glBindTextureUnit( 0/*unit*/, mPPTBFTexture ); // Set uniform(s) shaderProgram->set( 0, "uTexture" ); // Note: this uniform never changes => can be set after shaderprogram::link() // Draw command(s) glDrawArrays( GL_TRIANGLES, 0, 3 ); } PtShaderProgram::unuse(); // TEST: render HUD //mPointProcess->render(); #else //--------------------------------------------------- // TEST: color map //--------------------------------------------------- // Set shader program PtShaderProgram* shaderProgram = mColormapShaderProgram; shaderProgram->use(); { // Set texture(s) // - PPTBF (compositing) glBindTextureUnit( 0/*unit*/, mPPTBFTexture ); // - color map //glBindTextureUnit( 1/*unit*/, mColormapTexture ); // Set uniform(s) shaderProgram->set( 0, "uPPTBFTex" ); // Note: this uniform never changes => can be set after shaderprogram::link() shaderProgram->set( 1, "uColormapTex" ); //shaderProgram->set( getColormapIndex(), "uColormapIndex" ); // Draw command(s) glDrawArrays( GL_TRIANGLES, 0, 3 ); } PtShaderProgram::unuse(); #endif } /****************************************************************************** * Flag to tell whether or not to use full FBO resolution (slow "screen size" or faster "640x480" for editing) ******************************************************************************/ bool PtGraphicsPPTBF::useLowResolutionPPTBF() const { return mUseLowResolutionPPTBF; } /****************************************************************************** * Flag to tell whether or not to use full FBO resolution (slow "screen size" or faster "640x480" for editing) ******************************************************************************/ void PtGraphicsPPTBF::setUseLowResolutionPPTBF( const bool pFlag ) { mUseLowResolutionPPTBF = pFlag; mUpdateDeformation = true; mUpdatePointProcess = true; mUpdateWindowCellular = true; mUpdateFeature = true; onSizeModified( mWidth, mHeight ); } /****************************************************************************** * Generate database ******************************************************************************/ void PtGraphicsPPTBF::generateDatabase_test( const unsigned int pWidth, const unsigned int pHeight, const char* pPath ) { assert( pWidth != 0 && pHeight != 0 ); // LOG info std::cout << "\nPPTBF Database generation..." << std::endl; std::cout << "START..." << std::endl; const int width = pWidth; const int height = pHeight; // Resize graphics resources onSizeModified( width, height ); //const std::string databasePath = PtEnvironment::mDataPath + std::string( "/BDDStructure/Test/" ); const std::string databasePath = pPath; // Deformation std::vector< float > turbulenceAmplitude0Array; std::vector< float > turbulenceAmplitude1Array; std::vector< float > turbulenceAmplitude2Array; // Model Transform std::vector< int > modelResolutionArray; std::vector< float > modelAlphaArray; std::vector< float > modelRescalexArray; // Point process std::vector< int > tilingTypeArray; std::vector< float > jitteringArray; // Window function std::vector< int > windowShapeArray; std::vector< float > windowArityArray; std::vector< float > windowLarpArray; std::vector< float > windowNormArray; std::vector< float > windowSmoothArray; std::vector< float > windowBlendArray; std::vector< float > windowSigwcellArray; // Feature function std::vector< int > featureBombingArray; std::vector< float > featureNormArray; std::vector< float > featureWinfeatcorrelArray; std::vector< float > featureAnisoArray; std::vector< int > featureMinNbKernelsArray; std::vector< int > featureMaxNbKernelsArray; std::vector< float > featureSigcosArray; std::vector< float > featureSigcosvarArray; std::vector< int > featureFrequencyArray; std::vector< float > featurePhaseShiftArray; std::vector< float > featureThicknessArray; std::vector< float > featureCurvatureArray; std::vector< float > featureOrientationArray; /////////////////////////////////////////// // USER Experiment // - sampling the space of PPTBF structures /////////////////////////////////////////// #if 0 // Deformation turbulenceAmplitude0Array.push_back( 0.f ); turbulenceAmplitude1Array.push_back( 0.f ); turbulenceAmplitude2Array.push_back( 0.f ); // Model Transform modelResolutionArray.push_back( 100 ); modelAlphaArray.push_back( 0.f * M_PI ); modelRescalexArray.push_back( 1.f ); // Point process tilingTypeArray.push_back( 4 ); jitteringArray.push_back( 0.f ); // Window function windowShapeArray.push_back( 2 ); windowArityArray.push_back( 6.f ); windowLarpArray.push_back( 0.f ); windowNormArray.push_back( 2.f ); windowSmoothArray.push_back( 0.f ); windowBlendArray.push_back( 1.f ); windowSigwcellArray.push_back( 0.1f ); // Feature function featureBombingArray.push_back( 0 ); featureNormArray.push_back( 2.f ); featureWinfeatcorrelArray.push_back( 0.f ); featureAnisoArray.push_back( 10.f ); featureMinNbKernelsArray.push_back( 1 ); featureMaxNbKernelsArray.push_back( 2 ); featureSigcosArray.push_back( 1.f ); featureSigcosvarArray.push_back( 0.1f ); featureFrequencyArray.push_back( 0 ); featurePhaseShiftArray.push_back( 0.f ); featureThicknessArray.push_back( 0.01f ); featureCurvatureArray.push_back( 0.f ); featureOrientationArray.push_back( M_PI / 2.f ); #else ////////////// // Deformation ////////////// // Parameter 0 for ( float param_0 = 0.0f; param_0 <= 1.0f; param_0 += 0.25f ) { turbulenceAmplitude0Array.push_back( param_0 ); } // Parameter 1 for ( float param_1 = 0.0f; param_1 <= 1.0f; param_1 += 0.25f ) { turbulenceAmplitude1Array.push_back( param_1 ); } // Parameter 2 for ( float param_2 = 0.0f; param_2 <= 1.0f; param_2 += 0.25f ) { turbulenceAmplitude2Array.push_back( param_2 ); } ////////////////// // Model Transform ////////////////// // Resolution for ( int resolution = 100; resolution <= 1000; resolution += 100 ) { modelResolutionArray.push_back( resolution ); } // Alpha for ( float alpha = 0.f; alpha <= 2.f; alpha += 0.25f ) { modelAlphaArray.push_back( alpha * M_PI ); } // Rescale X for ( float rescalex = 1.0f; rescalex <= 4.f; rescalex += 0.5f ) { modelRescalexArray.push_back( rescalex ); } //////////////// // Point Process //////////////// // Tiling type //tilingTypeArray.resize( 18 ); //std::iota( tilingTypeArray.begin(), tilingTypeArray.end(), 0 ); //for ( int tileid = 0; tileid <= 17; tileid++ ) for ( int tileid = 4; tileid <= 17; tileid++ ) { tilingTypeArray.push_back( tileid ); } // Jittering for ( float jitter = 0.0f; jitter <= 1.0f; jitter += 0.8f ) { jitteringArray.push_back( jitter ); } ////////////////// // WINDOW FUNCTION ////////////////// // Shape //for ( int shape = 0; shape <= 3; shape += 1 ) for ( int shape = 2; shape <= 3; shape += 1 ) { windowShapeArray.push_back( shape ); } // Arity //for ( float windowArity = 2.f; windowArity <= 6.f; windowArity += 1.f ) for ( float windowArity = 6.f; windowArity <= 6.f; windowArity += 1.f ) { windowArityArray.push_back( windowArity ); } // Larp for ( float windowLarp = 0.f; windowLarp <= 1.f; windowLarp += 0.5f ) { windowLarpArray.push_back( windowLarp ); } // Norm //for ( float windowNorm = 1.f; windowNorm <= 3.f; windowNorm += 1.f ) for ( float windowNorm = 2.f; windowNorm <= 3.f; windowNorm += 1.f ) { windowNormArray.push_back( windowNorm ); } // Smooth for ( float windowSmooth = 0.f; windowSmooth <= 2.f; windowSmooth += 1.f ) { windowSmoothArray.push_back( windowSmooth ); } // Blend //for ( float windowBlend = 0.f; windowBlend <= 1.f; windowBlend += 0.25f ) for ( float windowBlend = 1.f; windowBlend <= 1.f; windowBlend += 0.25f ) { windowBlendArray.push_back( windowBlend ); } // Sigwcell //for ( float windowSigwcell = 0.f; windowSigwcell <= 1.f; windowSigwcell += 0.25f ) for ( float windowSigwcell = 0.1f; windowSigwcell <= 1.f; windowSigwcell += 0.25f ) { windowSigwcellArray.push_back( windowSigwcell ); } /////////////////// // Feature Function /////////////////// // Bombing for ( int bombing = 0; bombing <= 3; bombing += 1 ) { featureBombingArray.push_back( bombing ); } // Norm //for ( float norm = 1.0; norm <= 3.0; norm += 1.0 ) for ( float norm = 2.0; norm <= 3.0; norm += 1.0 ) { featureNormArray.push_back( norm ); } // Winfeatcorrel for ( float winfeatcorrel = 0.0; winfeatcorrel <= 10.0; winfeatcorrel += 1.0 ) { featureWinfeatcorrelArray.push_back( winfeatcorrel ); } // Anisotropy //for ( float anisotropy = 1.0; anisotropy <= 10.0; anisotropy += 1.0 ) for ( float anisotropy = 10.f; anisotropy <= 10.0; anisotropy += 1.0 ) { featureAnisoArray.push_back( anisotropy ); } // Min/Max number of kernels for ( int Npmin = 1; Npmin <= 8; Npmin += 4 ) { featureMinNbKernelsArray.push_back( Npmin ); for ( int Npmax = Npmin; Npmin <= 8; Npmin += 4 ) { featureMaxNbKernelsArray.push_back( Npmax ); } } // Sigcos //for ( float featureSigcos = 0.1f; featureSigcos <= 1.f; featureSigcos += 0.5f ) for ( float featureSigcos = 1.f; featureSigcos <= 1.f; featureSigcos += 0.5f ) { featureSigcosArray.push_back( featureSigcos ); } // Sigcosvar for ( float featureSigcosvar = 0.1f; featureSigcosvar <= 1.f; featureSigcosvar += 0.5f ) { featureSigcosvarArray.push_back( featureSigcosvar ); } // Frequency for ( int ifreq = 0; ifreq <= 3; ifreq += 1 ) { featureFrequencyArray.push_back( ifreq ); } // Phase for ( float phase = 0.0; phase <= 2.0; phase += 2.0 ) { featurePhaseShiftArray.push_back( phase * M_PI ); } // Thickness //for ( float thickness = 0.1; thickness <= 1.0; thickness += 0.4 ) for ( float thickness = 0.01f; thickness <= 1.0; thickness += 0.4 ) { featureThicknessArray.push_back( thickness ); } // Curvature for ( float curvature = 0.0; curvature <= 0.4; curvature += 0.2 ) { featureCurvatureArray.push_back( curvature ); } // Orientation for ( float deltaorient = 0.0; deltaorient <= M_PI / 2.0; deltaorient += M_PI / 4.0 ) { featureOrientationArray.push_back( deltaorient ); } #endif /////////////////////// // Set common GL states /////////////////////// //setImageWidth( width ); //setImageHeight( height ); setWidth( width ); setHeight( height ); // Set shader program PtShaderProgram* shaderProgram = mMegakernelShaderProgram; shaderProgram->use(); // Set texture(s) // - PRNG glBindTextureUnit( 0/*unit*/, mTexture_P ); // - noise glBindTextureUnit( 1/*unit*/, mTexture_rnd_tab ); // Set sampler(s) // - PRNG glBindSampler( 0/*unit*/, mSampler_PRNG_Noise ); // - noise glBindSampler( 1/*unit*/, mSampler_PRNG_Noise ); // Set image(s) // - PPTBF (output) glBindImageTexture( 0/*unit*/, mPPTBFTexture, 0/*level*/, GL_FALSE/*layered*/, 0/*layer*/, GL_WRITE_ONLY, GL_R32F ); // Set uniform(s) // - PRNG shaderProgram->set( 0, "uPermutationTex" ); // - noise shaderProgram->set( 1, "uNoiseTex" ); // Kernel configuration // - block const int blockSizeX = 8; // TODO: benchmark with 8x8, 16x16 and 32x32 const int blockSizeY = 8; // - grid const GLuint gridSizeX = glm::max( ( width + blockSizeX - 1 ) / blockSizeX, 1 ); const GLuint gridSizeY = glm::max( ( height + blockSizeY - 1 ) / blockSizeY, 1 ); ///////////////////////////////////////// // Sampling the space of PPTBF structures ///////////////////////////////////////// // Global PPTBF counter int i = 0; // Deformation int d_0 = 0; int d_1 = 0; int d_2 = 0; // Model Transform int m_0 = 0; int m_1 = 0; int m_2 = 0; // Point process int p_0 = 0; int p_1 = 0; // Window function int w_0 = 0; int w_1 = 0; int w_2 = 0; int w_3 = 0; int w_4 = 0; int w_5 = 0; int w_6 = 0; // Feature function int f_0 = 0; int f_1 = 0; int f_2 = 0; int f_3 = 0; int f_4 = 0; int f_5 = 0; int f_6 = 0; int f_7 = 0; int f_8 = 0; int f_9 = 0; int f_10 = 0; int f_11 = 0; int f_12 = 0; std::size_t nbSamples = 1; // Deformation nbSamples *= turbulenceAmplitude0Array.size(); nbSamples *= turbulenceAmplitude1Array.size(); nbSamples *= turbulenceAmplitude2Array.size(); // Model Transform nbSamples *= modelResolutionArray.size(); nbSamples *= modelAlphaArray.size(); nbSamples *= modelRescalexArray.size(); // Point process nbSamples *= tilingTypeArray.size(); nbSamples *= jitteringArray.size(); // Window function nbSamples *= windowShapeArray.size(); nbSamples *= windowArityArray.size(); nbSamples *= windowLarpArray.size(); nbSamples *= windowNormArray.size(); nbSamples *= windowSmoothArray.size(); nbSamples *= windowBlendArray.size(); nbSamples *= windowSigwcellArray.size(); // Feature function nbSamples *= featureBombingArray.size(); nbSamples *= featureNormArray.size(); nbSamples *= featureWinfeatcorrelArray.size(); nbSamples *= featureAnisoArray.size(); nbSamples *= featureMinNbKernelsArray.size(); nbSamples *= featureMaxNbKernelsArray.size(); nbSamples *= featureSigcosArray.size(); nbSamples *= featureSigcosvarArray.size(); nbSamples *= featureFrequencyArray.size(); nbSamples *= featurePhaseShiftArray.size(); nbSamples *= featureThicknessArray.size(); nbSamples *= featureCurvatureArray.size(); nbSamples *= featureOrientationArray.size(); ////////////// // Deformation ////////////// d_0 = 0; for ( const auto deformation_0 : turbulenceAmplitude0Array ) { shaderProgram->set( deformation_0, "uTurbulenceAmplitude_0" ); d_1 = 0; for ( const auto deformation_1 : turbulenceAmplitude1Array ) { shaderProgram->set( deformation_1, "uTurbulenceAmplitude_1" ); d_2 = 0; for ( const auto deformation_2 : turbulenceAmplitude2Array ) { shaderProgram->set( deformation_2, "uTurbulenceAmplitude_2" ); ////////////////// // Model Transform ////////////////// // Default translation shaderProgram->set( 0.f, "uShiftX" ); shaderProgram->set( 0.f, "uShiftY" ); m_0 = 0; for ( const auto modelResolution : modelResolutionArray ) { shaderProgram->set( modelResolution, "uResolution" ); m_1 = 0; for ( const auto modelAlpha : modelAlphaArray ) { shaderProgram->set( modelAlpha, "uRotation" ); m_2 = 0; for ( const auto modelRescalex : modelRescalexArray ) { shaderProgram->set( modelRescalex, "uRescaleX" ); //////////////// // Point Process //////////////// p_0 = 0; for ( const auto tilingType : tilingTypeArray ) { shaderProgram->set( tilingType, "uPointProcessTilingType" ); p_1 = 0; for ( const auto jittering : jitteringArray ) { shaderProgram->set( jittering, "uPointProcessJitter" ); ////////////////// // Window Function ////////////////// w_0 = 0; for ( const auto windowShape : windowShapeArray ) { shaderProgram->set( windowShape, "uWindowShape" ); w_1 = 0; for ( const auto windowArity : windowArityArray ) { shaderProgram->set( windowArity, "uWindowArity" ); w_2 = 0; for ( const auto windowLarp : windowLarpArray ) { shaderProgram->set( windowLarp, "uWindowLarp" ); w_3 = 0; for ( const auto windowNorm : windowNormArray ) { shaderProgram->set( windowNorm, "uWindowNorm" ); w_4 = 0; for ( const auto windowSmooth : windowSmoothArray ) { shaderProgram->set( windowSmooth, "uWindowSmooth" ); w_5 = 0; for ( const auto windowBlend : windowBlendArray ) { shaderProgram->set( windowBlend, "uWindowBlend" ); w_6 = 0; for ( const auto windowSigwcell : windowSigwcellArray ) { shaderProgram->set( windowSigwcell, "uWindowSigwcell" ); /////////////////// // Feature Function /////////////////// /* f_0 = 0; for ( const auto featureBombing : featureBombingArray ) { shaderProgram->set( featureBombing, "uFeatureBomb" ); f_1 = 0; for ( const auto featureNorm : featureNormArray ) { shaderProgram->set( featureNorm, "uFeatureNorm" ); f_2 = 0; for ( const auto featureWinfeatcorrel : featureWinfeatcorrelArray ) { shaderProgram->set( featureWinfeatcorrel, "uFeatureWinfeatcorrel" ); f_3 = 0; for ( const auto featureAniso : featureAnisoArray ) { shaderProgram->set( featureAniso, "uFeatureAniso" ); f_4 = 0; for ( const auto minNbGaborKernels : featureMinNbKernelsArray ) { shaderProgram->set( minNbGaborKernels, "uFeatureNpmin" ); f_5 = 0; for ( const auto maxNbGaborKernels : featureMaxNbKernelsArray ) { shaderProgram->set( maxNbGaborKernels, "uFeatureNpmax" ); f_6 = 0; for ( const auto featureSigcos : featureSigcosArray ) { shaderProgram->set( featureSigcos, "uFeatureSigcos" ); f_7 = 0; for ( const auto featureSigcosvar : featureSigcosvarArray ) { shaderProgram->set( featureSigcosvar, "uFeatureSigcosvar" ); f_8 = 0; for ( const auto gaborStripesFrequency : featureFrequencyArray ) { shaderProgram->set( gaborStripesFrequency, "uFeatureFreq" ); f_9 = 0; for ( const auto featurePhase : featurePhaseShiftArray ) { shaderProgram->set( featurePhase, "uFeaturePhase" ); f_10 = 0; for ( const auto gaborStripesThickness : featureThicknessArray ) { shaderProgram->set( gaborStripesThickness, "uFeatureThickness" ); f_11 = 0; for ( const auto gaborStripesCurvature : featureCurvatureArray ) { shaderProgram->set( gaborStripesCurvature, "uFeatureCourbure" ); f_12 = 0; for ( const auto gaborStripesOrientation : featureOrientationArray ) { shaderProgram->set( gaborStripesOrientation, "uFeatureDeltaorient" );*/ //--------------------- // Generate PPTBF image //--------------------- std::cout << "generating image: " << ( i + 1 ) << "/" << nbSamples << std::endl; // Launch mega-kernel glDispatchCompute( gridSizeX, gridSizeY, 1 ); // Synchronization // - make sure writing to image has finished before read glMemoryBarrier( GL_SHADER_IMAGE_ACCESS_BARRIER_BIT ); // pb: wait for nothing? use a boolean if someone need to sample texture glMemoryBarrier( GL_ALL_BARRIER_BITS ); //------------------- // Export PPTBF image //------------------- // Retrieve data on host std::vector< float > f_pptbf( width * height ); #if 1 // - deal with odd texture dimensions glPixelStorei( GL_PACK_ALIGNMENT, 1 ); #endif glGetTextureImage( mPPTBFTexture, 0/*level*/, GL_RED, GL_FLOAT, sizeof( float ) * width * height, f_pptbf.data() ); // Convert data (float to unsigned char) // TODO: maybe use for_each with a lambda doing the "cast" directly instead? std::transform( f_pptbf.begin(), f_pptbf.end(), f_pptbf.begin(), std::bind( std::multiplies< float >(), std::placeholders::_1, 255.f ) ); std::vector< unsigned char > u_pptbf( f_pptbf.begin(), f_pptbf.end() ); // Save data in image //const std::string pptbfName = std::string( "pptbf_" )/*name*/ + std::to_string( i ); const std::string pptbfName = std::string( "pptbf" )/*name*/ + std::string( "_D_" ) + std::to_string( d_0 ) + std::string( "_" ) + std::to_string( d_1 ) + std::string( "_" ) + std::to_string( d_2 ) + std::string( "_M_" ) + std::to_string( m_0 ) + std::string( "_" ) + std::to_string( m_1 ) + std::string( "_" ) + std::to_string( m_2 ) + std::string( "_P_" ) + std::to_string( p_0 ) + std::string( "_" ) + std::to_string( p_1 ) + std::string( "_W_" ) + std::to_string( w_0 ) + std::string( "_" ) + std::to_string( w_1 ) + std::string( "_" ) + std::to_string( w_2 ) + std::string( "_" ) + std::to_string( w_3 ) + std::string( "_" ) + std::to_string( w_4 ) + std::string( "_" ) + std::to_string( w_5 ) + std::string( "_" ) + std::to_string( w_6 ) + std::string( "_F_" ) + std::to_string( f_0 ) + std::string( "_" ) + std::to_string( f_1 ) + std::string( "_" ) + std::to_string( f_2 ) + std::string( "_" ) + std::to_string( f_3 ) + std::string( "_" ) + std::to_string( f_4 ) + std::string( "_" ) + std::to_string( f_5 ) + std::string( "_" ) + std::to_string( f_6 ) + std::string( "_" ) + std::to_string( f_7 ) + std::string( "_" ) + std::to_string( f_8 ) + std::string( "_" ) + std::to_string( f_9 ) + std::string( "_" ) + std::to_string( f_10 ) + std::string( "_" ) + std::to_string( f_11 ) + std::string( "_" ) + std::to_string( f_12 ); const std::string pptbfFilename = databasePath + pptbfName + std::string( ".png" ); PtImageHelper::saveImage( pptbfFilename.c_str(), width, height, 1/*nb channels*/, u_pptbf.data() ); // Update counter i++; /*} } } } } } } } } } } } }*/ w_6++; } w_5++; } w_4++; } w_3++; } w_2++; } w_1++; } w_0++; } p_1++; } p_0++; } m_2++; } m_1++; } m_0++; } d_2++; } d_1++; } d_0++; } // Reset GL state(s) // - Unset shader program PtShaderProgram::unuse(); // LOG info std::cout << "Finished..." << nbSamples << std::endl; } /****************************************************************************** * Generate database ******************************************************************************/ void PtGraphicsPPTBF::generateDatabase( const unsigned int pWidth, const unsigned int pHeight, const char* pPath, const unsigned int pSerieID ) { assert(pWidth != 0 && pHeight != 0); // LOG info std::cout << "\nPPTBF Database generation..." << std::endl; std::cout << "START..." << std::endl; const int width = pWidth; const int height = pHeight; // Resize graphics resources onSizeModified(width, height); //const std::string databasePath = PtEnvironment::mDataPath + std::string( "/BDDStructure/Test/" ); const std::string databasePath = pPath; // Deformation std::vector< float > turbulenceAmplitude0Array; std::vector< float > turbulenceAmplitude1Array; std::vector< float > turbulenceAmplitude2Array; // Model Transform std::vector< int > modelResolutionArray; std::vector< float > modelAlphaArray; std::vector< float > modelRescalexArray; // Point process std::vector< int > tilingTypeArray; std::vector< float > jitteringArray; // Window function std::vector< int > windowShapeArray; std::vector< float > windowArityArray; std::vector< float > windowLarpArray; std::vector< float > windowNormArray; std::vector< float > windowSmoothArray; std::vector< float > windowBlendArray; std::vector< float > windowSigwcellArray; // Feature function std::vector< int > featureBombingArray; std::vector< float > featureNormArray; std::vector< float > featureWinfeatcorrelArray; std::vector< float > featureAnisoArray; std::vector< int > featureMinNbKernelsArray; std::vector< int > featureMaxNbKernelsArray; std::vector< float > featureSigcosArray; std::vector< float > featureSigcosvarArray; std::vector< int > featureFrequencyArray; std::vector< float > featurePhaseShiftArray; std::vector< float > featureThicknessArray; std::vector< float > featureCurvatureArray; std::vector< float > featureOrientationArray; /////////////////////////////////////////// // USER Experiment // - sampling the space of PPTBF structures /////////////////////////////////////////// #if 0 // Deformation turbulenceAmplitude0Array.push_back(0.f); turbulenceAmplitude1Array.push_back(0.f); turbulenceAmplitude2Array.push_back(0.f); // Model Transform modelResolutionArray.push_back(100); modelAlphaArray.push_back(0.f * M_PI); modelRescalexArray.push_back(1.f); // Point process tilingTypeArray.push_back(4); jitteringArray.push_back(0.f); // Window function windowShapeArray.push_back(2); windowArityArray.push_back(6.f); windowLarpArray.push_back(0.f); windowNormArray.push_back(2.f); windowSmoothArray.push_back(0.f); windowBlendArray.push_back(1.f); windowSigwcellArray.push_back(0.1f); // Feature function featureBombingArray.push_back(0); featureNormArray.push_back(2.f); featureWinfeatcorrelArray.push_back(0.f); featureAnisoArray.push_back(10.f); featureMinNbKernelsArray.push_back(1); featureMaxNbKernelsArray.push_back(2); featureSigcosArray.push_back(1.f); featureSigcosvarArray.push_back(0.1f); featureFrequencyArray.push_back(0); featurePhaseShiftArray.push_back(0.f); featureThicknessArray.push_back(0.01f); featureCurvatureArray.push_back(0.f); featureOrientationArray.push_back(M_PI / 2.f); #else //int descriptor = 2; int descriptor = 1; //const int KEEPNBEST = 1; const int KEEPNBEST = 5; //const int NR = 100; const int NR = 10; float deltaalpha = 0.0; // 0.5 = pi/2 float factresol = 1.0; float factrescalex = 1.0; float ecart = 0.5; //char *exname = "TexturesCom_Asphalt11_2x2_1K_seg_scrop_80"; //char *exname = "TexturesCom_Pavement_CobblestoneForest01_4x4_1K_albedo_seg_scrop"; char *exname = "20181215_153153_seg_scrop_450"; const float KEEP_ERROR = 0.0; const int SS = 400; char pname[128]; int pptbf_count = 0; bool withwindowfile = true; int qthresh = 0; float percent = 0.2; int series_val[17 + 5 * 5 + 3 * 17][4] = { {0, 1, 0, 0},{ 1, 1, 0, 0 },{ 2, 1, 0, 0 },{ 3, 1, 0, 0 },{ 4, 1, 0, 0 },{ 5, 1, 0, 0 },{ 6, 1, 0, 0 },{ 7, 1, 0, 0 },{ 8, 1, 0, 0 },{ 9, 1, 0, 0 },{ 10, 1, 0, 0 },{ 11, 1, 0, 0 },{ 12, 1, 0, 0 },{ 13, 1, 0, 0 },{ 14, 1, 0, 0 },{ 15, 1, 0, 0 },{ 16, 1, 0, 0 }, { 0, 0, 1, 0 },{ 1, 0, 1, 0 },{ 7, 0, 1, 0 },{ 10, 0, 1, 0 },{ 14, 0, 1, 0 }, { 0, 0, 2, 0 },{ 1, 0, 2, 0 },{ 7, 0, 2, 0 },{ 10, 0, 2, 0 },{ 14, 0, 2, 0 }, { 0, 0, 3, 0 },{ 1, 0, 3, 0 },{ 7, 0, 3, 0 },{ 10, 0, 3, 0 },{ 14, 0, 3, 0 }, { 0, 0, 4, 0 },{ 1, 0, 4, 0 },{ 7, 0, 4, 0 },{ 10, 0, 4, 0 },{ 14, 0, 4, 0 }, { 0, 0, 2, 1 },{ 1, 0, 2, 1 },{ 7, 0, 2, 1 },{ 10, 0, 2, 1 },{ 14, 0, 2, 1 }, //{ 0, 0, 4, 1 },{ 1, 0, 4, 1 },{ 7, 0, 4, 1 },{ 10, 0, 4, 1 },{ 14, 0, 4, 1 }, { 0, 1, 1, 0 },{ 1, 1, 1, 0 },{ 2, 1, 1, 0 },{ 3, 1, 1, 0 },{ 4, 1, 1, 0 },{ 5, 1, 1, 0 },{ 6, 1, 1, 0 },{ 7, 1, 1, 0 },{ 8, 1, 1, 0 },{ 9, 1, 1, 0 },{ 10, 1, 1, 0 },{ 11, 1, 1, 0 },{ 12, 1, 1, 0 },{ 13, 1, 1, 0 },{ 14, 1, 1, 0 },{ 15, 1, 1, 0 },{ 16, 1, 1, 0 }, { 0, 1, 2, 0 },{ 1, 1, 2, 0 },{ 2, 1, 2, 0 },{ 3, 1, 2, 0 },{ 4, 1, 2, 0 },{ 5, 1, 2, 0 },{ 6, 1, 2, 0 },{ 7, 1, 2, 0 },{ 8, 1, 2, 0 },{ 9, 1, 2, 0 },{ 10, 1, 2, 0 },{ 11, 1, 2, 0 },{ 12, 1, 2, 0 },{ 13, 1, 2, 0 },{ 14, 1, 2, 0 },{ 15, 1, 2, 0 },{ 16, 1, 2, 0 }, { 0, 1, 2, 1 },{ 1, 1, 2, 1 },{ 2, 1, 2, 1 },{ 3, 1, 2, 1 },{ 4, 1, 2, 1 },{ 5, 1, 2, 1 },{ 6, 1, 2, 1 },{ 7, 1, 2, 1 },{ 8, 1, 2, 1 },{ 9, 1, 2, 1 },{ 10, 1, 2, 1 },{ 11, 1, 2, 1 },{ 12, 1, 2, 1 },{ 13, 1, 2, 1 },{ 14, 1, 2, 1 },{ 15, 1, 2, 1 },{ 16, 1, 2, 1 } }; //for (int do_serie = 0; do_serie <= 0; do_serie++) //{ //int do_serie = 17 + 5 * 5 + 2*17 + 16; // 17 + 5 * 5 + 0 * 17; int do_serie = pSerieID; // TODO: check bounds int do_tiling = series_val[do_serie][0]; // 0; // 0 - 17 int do_window = series_val[do_serie][1]; //1; // 0 or 1 int do_feature = series_val[do_serie][2]; // 0; // 0 - 4 int do_phase = series_val[do_serie][3]; //0; // 0 or 1 float jittering, wjittering, fjittering; int resolution, wresolution, fresolution; float rotation, wrotation, frotation; float rescalex, wrescalex, frescalex; float turbAmplitude0, turbAmplitude1, turbAmplitude2; float wturbAmplitude0, wturbAmplitude1, wturbAmplitude2; float fturbAmplitude0, fturbAmplitude1, fturbAmplitude2; int windowShape = do_window, wwindowShape, fwindowShape; float windowArity = 10.0, wwindowArity, fwindowArity; float windowLarp = 0.0, wwindowLarp, fwindowLarp; float windowNorm = 2.0, wwindowNorm, fwindowNorm; float windowSmoothness = 0.0, wwindowSmoothness, fwindowSmoothness; float windowBlend = 1.0, wwindowBlend, fwindowBlend; float windowSigwcell = 0.7, wwindowSigwcell, fwindowSigwcell; int featureBombing = 0, wfeatureBombing, ffeatureBombing; float featureNorm = 2.0, wfeatureNorm, ffeatureNorm; float featureWinfeatcorrel = 0.0, wfeatureWinfeatcorrel, ffeatureWinfeatcorrel; float featureAniso = 0.0, wfeatureAniso, ffeatureAniso; int featureMinNbKernels = 0, featureMaxNbKernels = 0; int wfeatureMinNbKernels = 0, wfeatureMaxNbKernels = 0; int ffeatureMinNbKernels = 0, ffeatureMaxNbKernels = 0; float featureSigcos = 1.0, wfeatureSigcos, ffeatureSigcos; float featureSigcosvar = 0.2, wfeatureSigcosvar, ffeatureSigcosvar; int featureFrequency = 0, wfeatureFrequency, ffeatureFrequency; float featurePhaseShift = (float)do_phase, wfeaturePhaseShift, ffeaturePhaseShift; float featureThickness = 1.0, wfeatureThickness, ffeatureThickness; float featureCurvature = 0.0, wfeatureCurvature, ffeatureCurvature; float featureOrientation = 0.0, wfeatureOrientation, ffeatureOrientation; #ifdef REFINEMENT sprintf(pname, "%s/pptbf_matching_rnd_%d.txt", pPath, descriptor); #else sprintf(pname, "%s/pptbf_%02d_%02d_%d_%d_%d.txt", pPath, do_serie, do_tiling, do_window, do_feature, do_phase); #endif FILE *fdn = fopen(pname, "w"); #ifndef REFINEMENT fprintf(fdn, "num jittering zoom rotation rescalex turbAmplitude0 turbAmplitude1 turbAmplitude2 windowShape windowArity windowLarp windowNorm windowSmoothness windowBlend windowSigwcell featureBombing featureNorm featureWinfeatcorrel featureAniso featureMinNbKernels featureMaxNbKernels featureSigcos featureSigcosvar featureFrequency featurePhaseShift featureThickness featureCurvature featureOrientation\n"); #endif #ifdef PROBE int tresolution; float tturbAmplitude0; sprintf(pname, "%s/gen_pptbf_%02d_%02d_%d_%d_%d.txt", pPath, do_serie, do_tiling, do_window, do_feature, do_phase); FILE *fdg = fopen(pname, "w"); sprintf(pname, "%s/pptbf_probe_%02d_%02d_%d_%d_%d.txt", pPath, do_serie, do_tiling, do_window, do_feature, do_phase); //sprintf(pname, "%s/pptbf_%02d_%02d_%d_%d_%d.txt", pPath, do_serie, do_tiling, do_window, do_feature, do_phase); FILE *fd = fopen(pname, "w"); fprintf(fd, "num jittering zoom rotation rescalex turbAmplitude0 turbAmplitude1 turbAmplitude2 windowShape windowArity windowLarp windowNorm windowSmoothness windowBlend windowSigwcell featureBombing featureNorm featureWinfeatcorrel featureAniso featureMinNbKernels featureMaxNbKernels featureSigcos featureSigcosvar featureFrequency featurePhaseShift featureThickness featureCurvature featureOrientation\n"); // only window function, featurefunct=cst, windowBlend=1 int resolutionArray[] = { 50 / 2, 150 / 2 }; //int resolutionArray[] = { 50, 150 }; if (!withwindowfile) { if (do_tiling == 2 || do_tiling >= 10) for (int i = 0; i < 2; i++) resolutionArray[i] *= 2; for (int iresolution = 0; iresolution <= 0; iresolution++) //for (int iresolution = 0; iresolution <= 1; iresolution++) { resolution = resolutionArray[iresolution]; tresolution = resolution * 2; float zoom = (float)SS / (float)resolutionArray[iresolution]; float rescalexArray[] = { 1.0, 3.0, 8.0 }; //for (int irescalex = 0; irescalex <= 2; irescalex++) for (int irescalex = 0; irescalex <= 0; irescalex++) { rescalex = rescalexArray[irescalex]; if (rescalex >= 5.0) resolution /= 2; else if (rescalex >= 2.5) resolution = resolution * 2 / 3; float rotstep = 1.0 / 8.0; //for (rotation = 0.0; rotation <= 1.0 / 8.0; rotation += rotstep) for (rotation = 0.0; rotation <= 0.0 / 8.0; rotation += rotstep) { float turbAmplitude0A[] = { 0.0, 0.06, 0.05, 0.03 }; float turbAmplitude1A[] = { 0.0, 0.05, 0.5, 0.8 }; float turbAmplitude2A[] = { 1.0, 1.0, 1.0, 1.0 }; for (int iturbAmplitude = 0; iturbAmplitude <= 0; iturbAmplitude++) { turbAmplitude0 = turbAmplitude0A[iturbAmplitude] * (float)resolution / (50.0 / 3.0); tturbAmplitude0 = turbAmplitude0A[iturbAmplitude] * pow((float)tresolution / 50.0, 1.6); turbAmplitude1 = turbAmplitude1A[iturbAmplitude]; turbAmplitude2 = turbAmplitude2A[iturbAmplitude]; float mjittering = 1.0; //if (do_window == 0) mjittering = 0.01; for (jittering = (do_serie < 42 ? 0.01 : 0.4); jittering <= mjittering; jittering += 0.45) { fprintf(fdg, "resol=%d, rescal=%g, rot=%g, iturbAmplitude=%d, jit=%g\n\n", resolution, rescalex, rotation, iturbAmplitude, jittering); /////////////////////////////////////// // WINDOW FUNCTION ONLY, FEATURE is constant windowShape = do_window; featureBombing = do_feature; featureNorm = 2.0; featureWinfeatcorrel = 0.0; featureAniso = 0.0; featureMinNbKernels = 0, featureMaxNbKernels = 0; featureSigcos = 3.0; featureSigcosvar = 0.2; featureFrequency = 0; featurePhaseShift = (float)do_phase; featureThickness = 1.0; featureCurvature = 0.0; featureOrientation = 0.0; //float windowBlendA[] = { 1.0, 0.5, 0.1 }; float windowBlendA[] = { 1.0, 0.5, 0.1 }; if (do_feature == 0 && do_window == 1) for (int iwindowBlend = 0; iwindowBlend <= 2; iwindowBlend += 1) { windowBlend = windowBlendA[iwindowBlend]; fprintf(fdg, "windowBlend=%g\n", windowBlend); int featureBombingA[] = { 0, 2, 5 }; for (int ifeatureBombing = 0; ifeatureBombing <= 0; ifeatureBombing++) //for (int ifeatureBombing = 0; ifeatureBombing <= (windowBlend>0.5?2:1); ifeatureBombing++) { featureBombing = featureBombingA[ifeatureBombing]; //if (featureBombing == 2) featurePhaseShift = 1.0; //else featurePhaseShift = 0.0; int lfeatureMinNbKernels = 0; if (featureBombing == 5) lfeatureMinNbKernels = 2; int efeatureMinNbKernels = 0; int sfeatureMinNbKernels = 1; if (featureBombing == 2) efeatureMinNbKernels = 2; else if (featureBombing == 5) efeatureMinNbKernels = 4; if (featureBombing == 5) sfeatureMinNbKernels = 3; for (featureMinNbKernels = lfeatureMinNbKernels; featureMinNbKernels <= efeatureMinNbKernels; featureMinNbKernels += 2) for (featureMaxNbKernels = featureMinNbKernels; featureMaxNbKernels <= featureMinNbKernels; featureMaxNbKernels += 4) //for (featureMaxNbKernels = featureMinNbKernels + sfeatureMinNbKernels; featureMaxNbKernels <= featureMinNbKernels + sfeatureMinNbKernels; featureMaxNbKernels += 4) { fprintf(fdg, "featureMinNbKernels=%g\n", featureMinNbKernels); for (featureWinfeatcorrel = 0.0; featureWinfeatcorrel <= 0.0; featureWinfeatcorrel += 0.6) //for (featureWinfeatcorrel = (featureBombing == 5 ? 0.5 : 0.0); featureWinfeatcorrel <= (featureBombing == 5 ? 0.5 : 0.0); featureWinfeatcorrel += 0.3) { fprintf(fdg, "featureWinfeatcorrel=%g\n", featureWinfeatcorrel); float lfeatureSigcos = 4.0; float efeatureSigcos = 4.0; if (featureBombing == 2) efeatureSigcos = 8.0; else if (featureBombing == 5) { lfeatureSigcos = 0.5; efeatureSigcos = 0.5; } for (featureSigcos = lfeatureSigcos; featureSigcos <= efeatureSigcos; featureSigcos += 4.0) { fprintf(fdg, "featureSigcos=%g\n", featureSigcos); float windowArityA[] = { 2.0, 3.0, 4.0, 8.0 }; for (int iwindowArity = (windowBlend <= 0.5 ? 3 : 0); iwindowArity <= 3; iwindowArity++) { windowArity = windowArityA[iwindowArity]; fprintf(fdg, "windowArity=%g\n", windowArity); float lwindowSmoothness = 2.0; if (windowArity >= 6.0) lwindowSmoothness = 0.0; else if (windowArity >= 5.0) lwindowSmoothness = 1.0; for (windowSmoothness = 0.0; windowSmoothness <= lwindowSmoothness; windowSmoothness += 1.0) { fprintf(fdg, "windowSmoothness=%g\n", windowSmoothness); float lwindowLarp = 1.0; float windowstepLarp = 0.25; if (windowArity <= 3.0) lwindowLarp = 0.0; else if (windowArity <= 5.0) lwindowLarp = 0.25; else windowstepLarp = 0.3; for (windowLarp = 0.0; windowLarp <= lwindowLarp; windowLarp += windowstepLarp) { fprintf(fdg, "windowLarp=%g\n", windowLarp); for (windowNorm = (windowBlend < 0.5 ? 3.0 : 2.0); windowNorm >= (windowLarp == 0.0 && windowArity > 5.0 ? 1.0 : 2.0); windowNorm -= 1.0) { fprintf(fdg, "windowNorm=%g\n", windowNorm); for (windowSigwcell = 1.0; windowSigwcell <= 1.7; windowSigwcell += 1.0) { fprintf(fdg, "windowSigwcell=%g\n", windowSigwcell); fprintf(fdg, "------------> do image %06d\n", pptbf_count); fprintf(fd, "%06d %g %d %g %g %g %g %g %d %g %g %g %g %g %g %d %g %g %g %d %d %g %g %d %g %g %g %g\n", pptbf_count, jittering, tresolution, rotation, rescalex, tturbAmplitude0, turbAmplitude1, turbAmplitude2, windowShape, windowArity, windowLarp, windowNorm, windowSmoothness, windowBlend, windowSigwcell, featureBombing, featureNorm, featureWinfeatcorrel, featureAniso, featureMinNbKernels, featureMaxNbKernels, featureSigcos, featureSigcosvar, featureFrequency, featurePhaseShift, featureThickness, featureCurvature, featureOrientation); pptbf_count++; // Deformation turbulenceAmplitude0Array.push_back(turbAmplitude0); turbulenceAmplitude1Array.push_back(turbAmplitude1); turbulenceAmplitude2Array.push_back(turbAmplitude2); // Model Transform modelResolutionArray.push_back(resolution); modelAlphaArray.push_back(rotation * M_PI); modelRescalexArray.push_back(rescalex); // Point process tilingTypeArray.push_back(do_tiling); jitteringArray.push_back(jittering); // Window function windowShapeArray.push_back(windowShape); windowArityArray.push_back(windowArity); windowLarpArray.push_back(windowLarp); windowNormArray.push_back(windowNorm); windowSmoothArray.push_back(windowSmoothness); windowBlendArray.push_back(windowBlend); windowSigwcellArray.push_back(windowSigwcell); // Feature function featureBombingArray.push_back(featureBombing); featureNormArray.push_back(featureNorm); featureWinfeatcorrelArray.push_back(featureWinfeatcorrel); featureAnisoArray.push_back(featureAniso); featureMinNbKernelsArray.push_back(featureMinNbKernels); featureMaxNbKernelsArray.push_back(featureMaxNbKernels); featureSigcosArray.push_back(featureSigcos); featureSigcosvarArray.push_back(featureSigcosvar); featureFrequencyArray.push_back(featureFrequency); featurePhaseShiftArray.push_back(featurePhaseShift*M_PI*0.5); featureThicknessArray.push_back(featureThickness); featureCurvatureArray.push_back(featureCurvature); featureOrientationArray.push_back(M_PI * featureOrientation); }//windowSigwcell }//windowNorm }//windowLarp }//windowSmoothness }//windowArity }//featureSigcos }//featureWinfeatcorrel }//featureMinNbKernels }//featureBombing }//windowBlend /////////////////////////////////////// // FEATURE FUNCTION only, Window is constant, resulting in blending (windowShape=0) windowShape = do_window; windowArity = 10.0; windowLarp = 0.0; windowNorm = 2.0; windowSmoothness = 0.0; windowBlend = 0.001; windowSigwcell = 0.5; featurePhaseShift = (float)do_phase; featureWinfeatcorrel = 0.0; //for (featureBombing = 2; featureBombing <= 2; featureBombing++) featureBombing = do_feature; if (do_feature > 0 && do_window == 0) //for (featureBombing = 1; featureBombing <= 4; featureBombing++) { float mfeatureAniso = 5.0; if (featureBombing == 5) mfeatureAniso = 0.0; else if (featureBombing == 4) mfeatureAniso = 2.5; for (featureAniso = 0.0; featureAniso <= mfeatureAniso; featureAniso += 2.5) { fprintf(fdg, "featureAniso=%g\n", featureAniso); int featureFrequencyA[] = { 0, 1, 2, 4, 8, 16, 32 }; //for (int ifeatureFrequency = 2; ifeatureFrequency <= (featureBombing == 1 || featureBombing == 2 ? 6 : 0); ifeatureFrequency++) //for (int ifeatureFrequency = 0; ifeatureFrequency <= (featureBombing == 1 || featureBombing == 2 ? 4 : 0); ifeatureFrequency++) for (int ifeatureFrequency = 0; ifeatureFrequency <= 4; ifeatureFrequency++) { featureFrequency = featureFrequencyA[ifeatureFrequency]; fprintf(fdg, "featureFrequency=%d\n", featureFrequency); for (featureNorm = (featureAniso >= 2.5 || featureBombing == 5 || featureBombing == 1 || featureBombing == 2 ? 2.0 : 1.0); featureNorm <= (featureAniso != 0.0 || featureBombing == 5 || featureBombing == 1 || featureBombing == 2 ? 2.0 : 3.0); featureNorm += 1.0) { fprintf(fdg, "featureNorm=%g\n", featureNorm); float lfeatureSigcos = (featureFrequency > 1 ? 1.0 : 2.0); float mfeatureSigcos = 1.0; float sfeatureSigcos = 1.0; if (featureBombing == 3) { lfeatureSigcos = 10.0; if (featureAniso > 4.0) { mfeatureSigcos = 10.0; } else if (featureAniso > 3.0) { mfeatureSigcos = 5.0; sfeatureSigcos = 4.0; } else if (featureAniso > 2.0) { mfeatureSigcos = 3.0; sfeatureSigcos = 3.0; } else if (featureAniso > 1.0) { mfeatureSigcos = 1.0; sfeatureSigcos = 3.0; } else { mfeatureSigcos = 0.75; sfeatureSigcos = 0.25; lfeatureSigcos = 1.25; } } else if (featureBombing == 4) { mfeatureSigcos = 0.25; lfeatureSigcos = 1.0; sfeatureSigcos = 0.75; } else if (featureBombing == 5) { mfeatureSigcos = 0.6; lfeatureSigcos = 1.0; sfeatureSigcos = 0.4; } for (featureSigcos = mfeatureSigcos; featureSigcos <= lfeatureSigcos; featureSigcos += sfeatureSigcos) { fprintf(fdg, "featureSigcos=%g\n", featureSigcos); for (featureMinNbKernels = (featureBombing == 5 ? 2 : 1); featureMinNbKernels <= (featureBombing == 5 ? 10 : 9); featureMinNbKernels += 4) for (featureMaxNbKernels = featureMinNbKernels; featureMaxNbKernels <= featureMinNbKernels; featureMaxNbKernels += 4) { fprintf(fdg, "featureMinNbKernels=%d\n", featureMinNbKernels); float featureCurvatureA[] = { 0.0, 0.2, 1.0 }; //for (int ifeatureCurvature = 2; ifeatureCurvature <= (ifeatureFrequency == 0 ? 0 : 2); ifeatureCurvature++) for (int ifeatureCurvature = 0; ifeatureCurvature <= (ifeatureFrequency == 0 ? 0 : 2); ifeatureCurvature++) { featureCurvature = featureCurvatureA[ifeatureCurvature]; fprintf(fdg, "featureCurvature=%g\n", featureCurvature); float ffeatureThickness = 0.1; if (ifeatureFrequency == 0) ffeatureThickness = 1.0; else if (featureFrequency > 10) ffeatureThickness = 0.5; if (featureBombing == 5) ffeatureThickness = 0.1; // for (featureThickness = (featureBombing == 5 ? 0.15 : 1.0); featureThickness >= ffeatureThickness; featureThickness -= (featureBombing == 5 ? 0.05 : 0.45)) for (featureThickness = (featureBombing == 5 ? 0.15 : 1.0); featureThickness >= ffeatureThickness; featureThickness -= (featureBombing == 5 ? 0.05 : 0.9)) { fprintf(fdg, "featureThickness=%g\n", featureThickness); float ffeatureOrientation = 0.5; if (ifeatureFrequency == 0 && featureAniso == 0.0) ffeatureOrientation = 0.0; if (featureCurvature > 0.9 && featureAniso == 0.0) ffeatureOrientation = 0.0; if (featureBombing >= 3) ffeatureOrientation = 0.5; if ((featureBombing == 3 || featureBombing == 4) && featureNorm == 2.0 && featureAniso == 0.0) ffeatureOrientation = 0.0; if ((featureBombing == 4) && featureNorm == 2.0 && featureAniso == 0.0) ffeatureOrientation = 0.0; if (featureBombing == 5) ffeatureOrientation = 0.0; for (featureOrientation = 0.0; featureOrientation <= ffeatureOrientation; featureOrientation += 0.15) { fprintf(fdg, "featureOrientation=%g\n", featureOrientation); for (featureWinfeatcorrel = 0.0; featureWinfeatcorrel <= 0.1; featureWinfeatcorrel += 0.5) { fprintf(fdg, "featureWinfeatcorrel=%g\n", featureWinfeatcorrel); fprintf(fdg, "------------> do image %06d\n", pptbf_count); //if (featureBombing == 5) printf("at %d\n", pptbf_count); fprintf(fd, "%06d %g %d %g %g %g %g %g %d %g %g %g %g %g %g %d %g %g %g %d %d %g %g %d %g %g %g %g\n", pptbf_count, jittering, tresolution, rotation, rescalex, tturbAmplitude0, turbAmplitude1, turbAmplitude2, windowShape, windowArity, windowLarp, windowNorm, windowSmoothness, windowBlend, windowSigwcell, featureBombing, featureNorm, featureWinfeatcorrel, featureAniso, featureMinNbKernels, featureMaxNbKernels, featureSigcos, featureSigcosvar, featureFrequency, featurePhaseShift, featureThickness, featureCurvature, featureOrientation); pptbf_count++; // Deformation turbulenceAmplitude0Array.push_back(turbAmplitude0); turbulenceAmplitude1Array.push_back(turbAmplitude1); turbulenceAmplitude2Array.push_back(turbAmplitude2); // Model Transform modelResolutionArray.push_back(resolution); modelAlphaArray.push_back(rotation * M_PI); modelRescalexArray.push_back(rescalex); // Point process tilingTypeArray.push_back(do_tiling); jitteringArray.push_back(jittering); // Window function windowShapeArray.push_back(windowShape); windowArityArray.push_back(windowArity); windowLarpArray.push_back(windowLarp); windowNormArray.push_back(windowNorm); windowSmoothArray.push_back(windowSmoothness); windowBlendArray.push_back(windowBlend); windowSigwcellArray.push_back(windowSigwcell); // Feature function featureBombingArray.push_back(featureBombing); featureNormArray.push_back(featureNorm); featureWinfeatcorrelArray.push_back(featureWinfeatcorrel); featureAnisoArray.push_back(featureAniso); featureMinNbKernelsArray.push_back(featureMinNbKernels); featureMaxNbKernelsArray.push_back(featureMaxNbKernels); featureSigcosArray.push_back(featureSigcos); featureSigcosvarArray.push_back(featureSigcosvar); featureFrequencyArray.push_back(featureFrequency); featurePhaseShiftArray.push_back(featurePhaseShift*M_PI*0.5); featureThicknessArray.push_back(featureThickness); featureCurvatureArray.push_back(featureCurvature); featureOrientationArray.push_back(M_PI * featureOrientation); }//featureWinfeatcorrel }//featureOrientation }//featureThickness }//featureCurvature }//featureMinNbKernels and featureMaxNbKernels }//featureSigcos }//featureNorm }//featureFrequency }//featureAniso }//featureBombing if (do_feature > 0 && do_feature != 3 && do_window == 1) { windowBlendA[1] = 0.6; for (int iwindowBlend = 0; iwindowBlend <= 1; iwindowBlend += 1) { windowBlend = windowBlendA[iwindowBlend]; fprintf(fdg, "windowBlend=%g\n", windowBlend); float mfeatureAniso = 5.0; if (featureBombing == 4) mfeatureAniso = 2.5; for (featureAniso = 0.0; featureAniso <= mfeatureAniso; featureAniso += 2.5) { fprintf(fdg, "featureAniso=%g\n", featureAniso); int featureFrequencyA[] = { 0, 1, 2 }; //for (int ifeatureFrequency = 2; ifeatureFrequency <= (featureBombing == 1 || featureBombing == 2 ? 6 : 0); ifeatureFrequency++) //for (int ifeatureFrequency = 0; ifeatureFrequency <= (featureBombing == 1 || featureBombing == 2 ? 4 : 0); ifeatureFrequency++) for (int ifeatureFrequency = 0; ifeatureFrequency <= 2; ifeatureFrequency += 2) { featureFrequency = featureFrequencyA[ifeatureFrequency]; fprintf(fdg, "featureFrequency=%d\n", featureFrequency); for (featureNorm = 2.0; featureNorm <= 2.0; featureNorm += 1.0) { fprintf(fdg, "featureNorm=%g\n", featureNorm); float lfeatureSigcos = (featureFrequency > 1 ? 1.0 : 2.0); float mfeatureSigcos = 1.0; float sfeatureSigcos = 1.0; if (featureBombing == 3) { lfeatureSigcos = 10.0; if (featureAniso > 4.0) { mfeatureSigcos = 10.0; } else if (featureAniso > 3.0) { mfeatureSigcos = 5.0; sfeatureSigcos = 4.0; } else if (featureAniso > 2.0) { mfeatureSigcos = 3.0; sfeatureSigcos = 3.0; } else if (featureAniso > 1.0) { mfeatureSigcos = 1.0; sfeatureSigcos = 3.0; } else { mfeatureSigcos = 0.75; sfeatureSigcos = 0.25; lfeatureSigcos = 1.25; } } for (featureSigcos = mfeatureSigcos; featureSigcos <= lfeatureSigcos; featureSigcos += sfeatureSigcos) { fprintf(fdg, "featureSigcos=%g\n", featureSigcos); for (featureMinNbKernels = 3; featureMinNbKernels <= 9; featureMinNbKernels += 6) for (featureMaxNbKernels = featureMinNbKernels; featureMaxNbKernels <= featureMinNbKernels; featureMaxNbKernels += 6) { fprintf(fdg, "featureMinNbKernels=%d\n", featureMinNbKernels); float featureCurvatureA[] = { 0.0, 0.2, 1.0 }; //for (int ifeatureCurvature = 2; ifeatureCurvature <= (ifeatureFrequency == 0 ? 0 : 2); ifeatureCurvature++) for (int ifeatureCurvature = 0; ifeatureCurvature <= (ifeatureFrequency == 0 ? 0 : 2); ifeatureCurvature += 2) { featureCurvature = featureCurvatureA[ifeatureCurvature]; fprintf(fdg, "featureCurvature=%g\n", featureCurvature); float ffeatureThickness = 0.1; if (ifeatureFrequency == 0) ffeatureThickness = 1.0; else if (featureFrequency > 10) ffeatureThickness = 0.5; if (featureBombing == 5) ffeatureThickness = 0.1; // for (featureThickness = (featureBombing == 5 ? 0.15 : 1.0); featureThickness >= ffeatureThickness; featureThickness -= (featureBombing == 5 ? 0.05 : 0.45)) for (featureThickness = (featureBombing == 5 ? 0.15 : 1.0); featureThickness >= ffeatureThickness; featureThickness -= (featureBombing == 5 ? 0.05 : 0.9)) { fprintf(fdg, "featureThickness=%g\n", featureThickness); float ffeatureOrientation = 0.5; if (ifeatureFrequency == 0 && featureAniso == 0.0) ffeatureOrientation = 0.0; if (featureCurvature > 0.9 && featureAniso == 0.0) ffeatureOrientation = 0.0; if (featureBombing >= 3) ffeatureOrientation = 0.5; if ((featureBombing == 3 || featureBombing == 4) && featureNorm == 2.0 && featureAniso == 0.0) ffeatureOrientation = 0.0; if ((featureBombing == 4) && featureNorm == 2.0 && featureAniso == 0.0) ffeatureOrientation = 0.0; //if (featureBombing == 5) ffeatureOrientation = 0.0; for (featureOrientation = 0.0; featureOrientation <= ffeatureOrientation; featureOrientation += 0.25) { fprintf(fdg, "featureOrientation=%g\n", featureOrientation); float windowArityA[] = { 2.0, 3.0, 4.0, 8.0 }; for (int iwindowArity = 1; iwindowArity <= 3; iwindowArity += 2) { windowArity = windowArityA[iwindowArity]; fprintf(fdg, "windowArity=%g\n", windowArity); float lwindowSmoothness = 2.0; if (windowArity >= 6.0) lwindowSmoothness = 0.0; else if (windowArity >= 5.0) lwindowSmoothness = 1.0; for (windowSmoothness = 0.0; windowSmoothness <= lwindowSmoothness; windowSmoothness += 2.0) { fprintf(fdg, "windowSmoothness=%g\n", windowSmoothness); float lwindowLarp = 0.5; if (windowArity <= 3.0) lwindowLarp = 0.0; else if (windowArity <= 5.0) lwindowLarp = 0.25; //if (jittering<0.1) lwindowLarp = 0.0; for (windowLarp = 0.0; windowLarp <= lwindowLarp; windowLarp += 0.25) //float lwindowLarp = 1.0; //float windowstepLarp = 0.25; //if (windowArity <= 3.0) lwindowLarp = 0.0; //else if (windowArity <= 5.0) lwindowLarp = 0.25; //else windowstepLarp = 0.3; //for (windowLarp = 0.0; windowLarp <= lwindowLarp; windowLarp += windowstepLarp) { fprintf(fdg, "windowLarp=%g\n", windowLarp); for (windowNorm = 2.0; windowNorm >= 2.0; windowNorm -= 1.0) { fprintf(fdg, "windowNorm=%g\n", windowNorm); float windowSigwcells = 1.0; //if (windowBlend <= 0.7) windowSigwcells = 0.7; for (windowSigwcell = windowSigwcells; windowSigwcell <= 1.5; windowSigwcell += 0.8) { fprintf(fdg, "windowSigwcell=%g\n", windowSigwcell); for (featureWinfeatcorrel = 0.0; featureWinfeatcorrel <= 0.6; featureWinfeatcorrel += 0.5) { fprintf(fdg, "featureWinfeatcorrel=%g\n", featureWinfeatcorrel); fprintf(fdg, "------------> do image %06d\n", pptbf_count); //if (featureBombing == 5) printf("at %d\n", pptbf_count); fprintf(fd, "%06d %g %d %g %g %g %g %g %d %g %g %g %g %g %g %d %g %g %g %d %d %g %g %d %g %g %g %g\n", pptbf_count, jittering, tresolution, rotation, rescalex, tturbAmplitude0, turbAmplitude1, turbAmplitude2, windowShape, windowArity, windowLarp, windowNorm, windowSmoothness, windowBlend, windowSigwcell, featureBombing, featureNorm, featureWinfeatcorrel, featureAniso, featureMinNbKernels, featureMaxNbKernels, featureSigcos, featureSigcosvar, featureFrequency, featurePhaseShift, featureThickness, featureCurvature, featureOrientation); pptbf_count++; // Deformation turbulenceAmplitude0Array.push_back(turbAmplitude0); turbulenceAmplitude1Array.push_back(turbAmplitude1); turbulenceAmplitude2Array.push_back(turbAmplitude2); // Model Transform modelResolutionArray.push_back(resolution); modelAlphaArray.push_back(rotation * M_PI); modelRescalexArray.push_back(rescalex); // Point process tilingTypeArray.push_back(do_tiling); jitteringArray.push_back(jittering); // Window function windowShapeArray.push_back(windowShape); windowArityArray.push_back(windowArity); windowLarpArray.push_back(windowLarp); windowNormArray.push_back(windowNorm); windowSmoothArray.push_back(windowSmoothness); windowBlendArray.push_back(windowBlend); windowSigwcellArray.push_back(windowSigwcell); // Feature function featureBombingArray.push_back(featureBombing); featureNormArray.push_back(featureNorm); featureWinfeatcorrelArray.push_back(featureWinfeatcorrel); featureAnisoArray.push_back(featureAniso); featureMinNbKernelsArray.push_back(featureMinNbKernels); featureMaxNbKernelsArray.push_back(featureMaxNbKernels); featureSigcosArray.push_back(featureSigcos); featureSigcosvarArray.push_back(featureSigcosvar); featureFrequencyArray.push_back(featureFrequency); featurePhaseShiftArray.push_back(featurePhaseShift*M_PI*0.5); featureThicknessArray.push_back(featureThickness); featureCurvatureArray.push_back(featureCurvature); featureOrientationArray.push_back(M_PI * featureOrientation); }//featureWinfeatcorrel }//windowSigwcell }//windowNorm }//windowLarp }//windowSmoothness }//windowArity }//featureOrientation }//featureThickness }//featureCurvature }//featureMinNbKernels and featureMaxNbKernels }//featureSigcos }//featureNorm }//featureFrequency }//featureAniso }//featureBombing } //windowBlend fflush(fdg); }//jittering }//turbulence }//rotation } // rescalex }//resolution } else { sprintf(pname, "%s/pptbf_window.txt", pPath); FILE *wfd = fopen(pname, "r"); char buff[2048], rdbuff[10]; int num; fgets(buff, 1000, wfd); // skip first line fgets(buff, 1000, wfd); fprintf(fdg, "%s <window>\n", buff); fflush(fdg); bool contw = true; int pptbf_countw = 0; do { sscanf(buff, "%d %g %d %g %g %g %g %g %d %g %g %g %g %g %g %d %g %g %g %d %d %g %g %d %g %g %g %g\n", &num, &wjittering, &wresolution, &wrotation, &wrescalex, &wturbAmplitude0, &wturbAmplitude1, &wturbAmplitude2, &wwindowShape, &wwindowArity, &wwindowLarp, &wwindowNorm, &wwindowSmoothness, &wwindowBlend, &wwindowSigwcell, &wfeatureBombing, &wfeatureNorm, &wfeatureWinfeatcorrel, &wfeatureAniso, &wfeatureMinNbKernels, &wfeatureMaxNbKernels, &wfeatureSigcos, &wfeatureSigcosvar, &wfeatureFrequency, &wfeaturePhaseShift, &wfeatureThickness, &wfeatureCurvature, &wfeatureOrientation); if (num == pptbf_countw) { contw = true; sprintf(pname, "%s/pptbf_feature.txt", pPath); FILE *ffd = fopen(pname, "r"); fgets(buff, 1000, ffd); // skip first line fgets(buff, 1000, ffd); fprintf(fdg, "%s <feature>\n", buff); fflush(fdg); bool contf = true; int pptbf_countf = 0; do { contf = true; sscanf(buff, "%d %g %d %g %g %g %g %g %d %g %g %g %g %g %g %d %g %g %g %d %d %g %g %d %g %g %g %g\n", &num, &fjittering, &fresolution, &frotation, &frescalex, &fturbAmplitude0, &fturbAmplitude1, &fturbAmplitude2, &fwindowShape, &fwindowArity, &fwindowLarp, &fwindowNorm, &fwindowSmoothness, &fwindowBlend, &fwindowSigwcell, &ffeatureBombing, &ffeatureNorm, &ffeatureWinfeatcorrel, &ffeatureAniso, &ffeatureMinNbKernels, &ffeatureMaxNbKernels, &ffeatureSigcos, &ffeatureSigcosvar, &ffeatureFrequency, &ffeaturePhaseShift, &ffeatureThickness, &ffeatureCurvature, &ffeatureOrientation); if (num == pptbf_countf) { turbAmplitude0 = wturbAmplitude0; turbAmplitude1 = wturbAmplitude1; turbAmplitude2 = wturbAmplitude2; resolution = wresolution; rotation = wrotation; rescalex = wrescalex; jittering = wjittering; windowShape = wwindowShape; windowArity = wwindowArity; windowNorm = wwindowNorm; windowSmoothness = wwindowSmoothness; windowBlend = wwindowBlend; windowLarp = wwindowLarp; windowSigwcell = wwindowSigwcell; featureBombing = ffeatureBombing; featureNorm = ffeatureNorm; featureWinfeatcorrel = ffeatureWinfeatcorrel; featureAniso = ffeatureAniso; featureMinNbKernels = ffeatureMinNbKernels; featureMaxNbKernels = ffeatureMaxNbKernels; featureSigcos = ffeatureSigcos; featureSigcosvar = ffeatureSigcosvar; featureFrequency = ffeatureFrequency; featurePhaseShift = ffeaturePhaseShift; featureThickness = ffeatureThickness; featureCurvature = ffeatureCurvature; featureOrientation = ffeatureOrientation; for (windowBlend = 0.6; windowBlend <= 1.1; windowBlend += 0.4) { for (featureWinfeatcorrel = 0.0; featureWinfeatcorrel <= 0.8; featureWinfeatcorrel += 0.7) { fprintf(fd, "%06d %g %d %g %g %g %g %g %d %g %g %g %g %g %g %d %g %g %g %d %d %g %g %d %g %g %g %g\n", pptbf_count, jittering, resolution, rotation, rescalex, turbAmplitude0, turbAmplitude1, turbAmplitude2, windowShape, windowArity, windowLarp, windowNorm, windowSmoothness, windowBlend, windowSigwcell, featureBombing, featureNorm, featureWinfeatcorrel, featureAniso, featureMinNbKernels, featureMaxNbKernels, featureSigcos, featureSigcosvar, featureFrequency, featurePhaseShift, featureThickness, featureCurvature, featureOrientation); // Deformation turbulenceAmplitude0Array.push_back(turbAmplitude0); turbulenceAmplitude1Array.push_back(turbAmplitude1); turbulenceAmplitude2Array.push_back(turbAmplitude2); // Model Transform modelResolutionArray.push_back(resolution); modelAlphaArray.push_back(rotation * M_PI); modelRescalexArray.push_back(rescalex); // Point process tilingTypeArray.push_back(do_tiling); jitteringArray.push_back(jittering); // Window function windowShapeArray.push_back(windowShape); windowArityArray.push_back(windowArity); windowLarpArray.push_back(windowLarp); windowNormArray.push_back(windowNorm); windowSmoothArray.push_back(windowSmoothness); windowBlendArray.push_back(windowBlend); windowSigwcellArray.push_back(windowSigwcell); // Feature function featureBombingArray.push_back(featureBombing); featureNormArray.push_back(featureNorm); featureWinfeatcorrelArray.push_back(featureWinfeatcorrel); featureAnisoArray.push_back(featureAniso); featureMinNbKernelsArray.push_back(featureMinNbKernels); featureMaxNbKernelsArray.push_back(featureMaxNbKernels); featureSigcosArray.push_back(featureSigcos); featureSigcosvarArray.push_back(featureSigcosvar); featureFrequencyArray.push_back(featureFrequency); featurePhaseShiftArray.push_back(featurePhaseShift*M_PI*0.5); featureThicknessArray.push_back(featureThickness); featureCurvatureArray.push_back(featureCurvature); featureOrientationArray.push_back(M_PI * featureOrientation); pptbf_count++; } } pptbf_countf++; fgets(buff, 1000, ffd); fprintf(fdg, "%s <feature>\n", buff); fflush(fdg); } else contf = false; } while (contf); fclose(ffd); pptbf_countw++; fgets(buff, 1000, wfd); fprintf(fdg, "%s <window>\n", buff); fflush(fdg); } else contw = false; } while (contw); fclose(wfd); } fclose(fdg); fclose(fd); #endif #ifdef PRODUCT sprintf(pname, "%s/pptbf_probe_%02d_%02d_%d_%d_%d.txt", pPath, do_serie, do_tiling, do_window, do_feature, do_phase); FILE *fd = fopen(pname, "r"); //sprintf(pname, "%s/pptbf_%02d_%02d_%d_%d_%d.txt", pPath, do_serie, do_tiling, do_window, do_feature, do_phase); //FILE *fdn = fopen(pname, "w"); //fprintf(fdn, "num jittering zoom rotation rescalex turbAmplitude0 turbAmplitude1 turbAmplitude2 windowShape windowArity windowLarp windowNorm windowSmoothness windowBlend windowSigwcell featureBombing featureNorm featureWinfeatcorrel featureAniso featureMinNbKernels featureMaxNbKernels featureSigcos featureSigcosvar featureFrequency featurePhaseShift featureThickness featureCurvature featureOrientation\n"); char buff[2048]; int num; fgets(buff, 1000, fd); // skip first line fgets(buff, 1000, fd); bool cont = true; int pptbf_countf = 0; do { sscanf(buff, "%d %g %d %g %g %g %g %g %d %g %g %g %g %g %g %d %g %g %g %d %d %g %g %d %g %g %g %g\n", &num, &jittering, &resolution, &rotation, &rescalex, &turbAmplitude0, &turbAmplitude1, &turbAmplitude2, &windowShape, &windowArity, &windowLarp, &windowNorm, &windowSmoothness, &windowBlend, &windowSigwcell, &featureBombing, &featureNorm, &featureWinfeatcorrel, &featureAniso, &featureMinNbKernels, &featureMaxNbKernels, &featureSigcos, &featureSigcosvar, &featureFrequency, &featurePhaseShift, &featureThickness, &featureCurvature, &featureOrientation); if (num == pptbf_countf) { cont = true; int resolutionArray[] = { 40 / 2, 100/2, 150 / 2 }; if (do_tiling == 2 || do_tiling >= 10) for (int i = 0; i < 4; i++) resolutionArray[i] *= 2; #ifdef WTRANSF for (int iresolution = 0; iresolution <= 2; iresolution++) #else for (int iresolution = 1; iresolution <= 1; iresolution++) #endif { resolution = resolutionArray[iresolution]; float zoom = (float)SS / (float)resolutionArray[iresolution]; float rescalexArray[] = { 1.0, 3.0, 6.0 }; #ifdef WTRANSF for (int irescalex = 0; irescalex <= 1; irescalex++) #else for (int irescalex = 0; irescalex <= 0; irescalex++) #endif { rescalex = rescalexArray[irescalex]; //if (rescalex >= 5.0) resolution *= 2; if (rescalex >= 5.0) resolution = (resolution * 4) / 3; float rotstep = 1.0 / 8.0; #ifdef WTRANSF for (rotation = 0.0; rotation <= 1.0 / 8.0; rotation += rotstep) #else for (rotation = 0.0; rotation <= 0.0 / 8.0; rotation += rotstep) #endif { //float turbAmplitude0A[] = { 0.0, 0.06, 0.05, 0.03, 0.06, 0.05, 0.02 }; //float turbAmplitude1A[] = { 0.0, 0.05, 0.5, 0.8, 0.05, 0.5, 0.5 }; //float turbAmplitude2A[] = { 1.0, 1.0, 1.0, 1.0, 2.0, 2.0, 4.0 }; float turbAmplitude0A[] = { 0.0, 0.06, 0.05, 0.06, 0.05}; float turbAmplitude1A[] = { 0.0, 0.05, 0.5, 0.05, 0.5}; float turbAmplitude2A[] = { 1.0, 1.0, 1.0, 2.0, 2.0}; #ifdef WTRANSF for (int iturbAmplitude = 0; iturbAmplitude <= 3; iturbAmplitude++) #else for (int iturbAmplitude = 0; iturbAmplitude <= 0; iturbAmplitude++) #endif { turbAmplitude0 = turbAmplitude0A[iturbAmplitude] * (float)resolution / (50.0 / 1.0); turbAmplitude1 = turbAmplitude1A[iturbAmplitude]; turbAmplitude2 = turbAmplitude2A[iturbAmplitude]; // Deformation turbulenceAmplitude0Array.push_back(turbAmplitude0); turbulenceAmplitude1Array.push_back(turbAmplitude1); turbulenceAmplitude2Array.push_back(turbAmplitude2); // Model Transform modelResolutionArray.push_back(resolution); modelAlphaArray.push_back(rotation * M_PI); modelRescalexArray.push_back(rescalex); // Point process tilingTypeArray.push_back(do_tiling); jitteringArray.push_back(jittering); // Window function windowShapeArray.push_back(windowShape); windowArityArray.push_back(windowArity); windowLarpArray.push_back(windowLarp); windowNormArray.push_back(windowNorm); windowSmoothArray.push_back(windowSmoothness); windowBlendArray.push_back(windowBlend); windowSigwcellArray.push_back(windowSigwcell); // Feature function featureBombingArray.push_back(featureBombing); featureNormArray.push_back(featureNorm); featureWinfeatcorrelArray.push_back(featureWinfeatcorrel); featureAnisoArray.push_back(featureAniso); featureMinNbKernelsArray.push_back(featureMinNbKernels); featureMaxNbKernelsArray.push_back(featureMaxNbKernels); featureSigcosArray.push_back(featureSigcos); featureSigcosvarArray.push_back(featureSigcosvar); featureFrequencyArray.push_back(featureFrequency); featurePhaseShiftArray.push_back(featurePhaseShift*M_PI*0.5); featureThicknessArray.push_back(featureThickness); featureCurvatureArray.push_back(featureCurvature); featureOrientationArray.push_back(M_PI * featureOrientation); //fprintf(fdn, "%06d %g %d %g %g %g %g %g %d %g %g %g %g %g %g %d %g %g %g %d %d %g %g %d %g %g %g %g\n", pptbf_count, jittering, resolution, rotation, rescalex, turbAmplitude0, turbAmplitude1, turbAmplitude2, // windowShape, windowArity, windowLarp, windowNorm, windowSmoothness, windowBlend, windowSigwcell, // featureBombing, featureNorm, featureWinfeatcorrel, featureAniso, featureMinNbKernels, featureMaxNbKernels, featureSigcos, featureSigcosvar, featureFrequency, featurePhaseShift, featureThickness, featureCurvature, featureOrientation); pptbf_count++; } } } } pptbf_countf++; fgets(buff, 1000, fd); } else cont = false; } while (cont); // fclose(fdn); // Close files fclose(fd); ///////////////////////////////////////////////////////////////////////////////////////////////////////// // LOG info //std::cout << "Finished..." << pptbf_count << std::endl; //return; ///////////////////////////////////////////////////////////////////////////////////////////////////////// #endif #ifdef REFINEMENT int pptbf_countf = 0; sprintf(pname, "%s/%s_best_pptbfparams_%d.txt", pPath, exname, descriptor); FILE *fd = fopen(pname, "r"); //sprintf(pname, "%s/pptbf_%02d_%02d_%d_%d_%d.txt", pPath, do_serie, do_tiling, do_window, do_feature, do_phase); //FILE *fdn = fopen(pname, "w"); //fprintf(fdn, "num jittering zoom rotation rescalex turbAmplitude0 turbAmplitude1 turbAmplitude2 windowShape windowArity windowLarp windowNorm windowSmoothness windowBlend windowSigwcell featureBombing featureNorm featureWinfeatcorrel featureAniso featureMinNbKernels featureMaxNbKernels featureSigcos featureSigcosvar featureFrequency featurePhaseShift featureThickness featureCurvature featureOrientation\n"); char buff1[2048], buff2[2048], buff3[2048]; int num; fgets(buff1, 1000, fd); sscanf(buff1, "%g", &percent); percent = 1.0 - percent; fgets(buff1, 1000, fd); fgets(buff2, 1000, fd); fgets(buff3, 1000, fd); bool cont = true; do { sscanf(buff1, "%02d %02d %d %d %d", &do_serie, &do_tiling, &do_window, &do_feature, &do_phase); sscanf(buff3, "%d %g %d %g %g %g %g %g %d %g %g %g %g %g %g %d %g %g %g %d %d %g %g %d %g %g %g %g\n", &num, &jittering, &resolution, &rotation, &rescalex, &turbAmplitude0, &turbAmplitude1, &turbAmplitude2, &windowShape, &windowArity, &windowLarp, &windowNorm, &windowSmoothness, &windowBlend, &windowSigwcell, &featureBombing, &featureNorm, &featureWinfeatcorrel, &featureAniso, &featureMinNbKernels, &featureMaxNbKernels, &featureSigcos, &featureSigcosvar, &featureFrequency, &featurePhaseShift, &featureThickness, &featureCurvature, &featureOrientation); if (pptbf_countf < KEEPNBEST) { cont = true; bool initial = true; for (int iresolution = 0; iresolution < NR; iresolution++) //for (int iresolution = 0; iresolution <= 0; iresolution++) { int nresolution = (int)(factresol*(double)resolution*(1.0f + (initial ? 0.0 : 0.25*ecart)*(2.0f*(float)rand() / (float)RAND_MAX - 1.0f))); float zoom = (float)SS / (float)nresolution; float njittering = jittering*(1.0f + (initial ? 0.0 : ecart)*(2.0f*(float)rand() / (float)RAND_MAX - 1.0f)); if (iresolution >= NR / 2 && !initial) njittering = (float)rand() / (float)RAND_MAX; if (njittering >= 1.0) njittering = 0.99; float nrescalex = factrescalex*rescalex*(1.0f + (initial ? 0.0 : 0.5*ecart)*(2.0f*(float)rand() / (float)RAND_MAX - 1.0f)); float turbAmplitude0A[] = { 0.0, 0.06, 0.05, 0.03, 0.06, 0.05, 0.02 }; float turbAmplitude1A[] = { 0.0, 0.05, 0.5, 0.8, 0.05, 0.5, 0.5 }; float turbAmplitude2A[] = { 1.0, 1.0, 1.0, 1.0, 2.0, 2.0, 4.0 }; float nturbAmplitude0 = turbAmplitude0*(1.0f + (initial ? 0.0 : 0.5*ecart)*(2.0f*(float)rand() / (float)RAND_MAX - 1.0f)); float nturbAmplitude1 = turbAmplitude1*(1.0f + (initial ? 0.0 : 0.5*ecart)*(2.0f*(float)rand() / (float)RAND_MAX - 1.0f)); float nturbAmplitude2 = turbAmplitude2*(1.0f + (initial ? 0.0 : 0.5*ecart)*(2.0f*(float)rand() / (float)RAND_MAX - 1.0f)); if (iresolution >= NR / 2 && !initial) nturbAmplitude0 = turbAmplitude0A[(iresolution - 1) % 6+1]* (1.0+0.2*ecart*(2.0f*(float)rand() / (float)RAND_MAX - 1.0f))* (float)nresolution / (50.0 / 1.0); if (iresolution >= NR / 2 && !initial) nturbAmplitude1 = turbAmplitude1A[(iresolution - 1) % 6+1] * (1.0 + 0.2*ecart*(2.0f*(float)rand() / (float)RAND_MAX - 1.0f)); if (iresolution >= NR / 2 && !initial) nturbAmplitude2 = turbAmplitude2A[(iresolution - 1) % 6+1] * (1.0 + 0.2*ecart*(2.0f*(float)rand() / (float)RAND_MAX - 1.0f)); // Deformation turbulenceAmplitude0Array.push_back(nturbAmplitude0); turbulenceAmplitude1Array.push_back(nturbAmplitude1); turbulenceAmplitude2Array.push_back(nturbAmplitude2); // Model Transform modelResolutionArray.push_back(nresolution); modelAlphaArray.push_back((rotation+ deltaalpha) * M_PI); modelRescalexArray.push_back(nrescalex); // Point process tilingTypeArray.push_back(do_tiling); jitteringArray.push_back(njittering); // Window function float nwindowArity= windowArity*(1.0f + (initial ? 0.0 : 0.5*ecart)*(2.0f*(float)rand() / (float)RAND_MAX - 1.0f)); if (nwindowArity <= 3.0) nwindowArity = 3.0; nwindowArity = floor(nwindowArity); windowShapeArray.push_back(windowShape); windowArityArray.push_back(windowArity); windowLarpArray.push_back(windowLarp*(1.0f + (initial ? 0.0 : 0.2*ecart)*(2.0f*(float)rand() / (float)RAND_MAX - 1.0f))); windowNormArray.push_back(windowNorm); windowSmoothArray.push_back(windowSmoothness*(1.0f + (initial ? 0.0 : 0.2*ecart)*(2.0f*(float)rand() / (float)RAND_MAX - 1.0f))); windowBlendArray.push_back(windowBlend); windowSigwcellArray.push_back(windowSigwcell); // Feature function featureBombingArray.push_back(featureBombing); featureNormArray.push_back(featureNorm); featureWinfeatcorrelArray.push_back(featureWinfeatcorrel*(1.0f + (initial ? 0.0 : 0.5*ecart)*(2.0f*(float)rand() / (float)RAND_MAX - 1.0f))); featureAnisoArray.push_back(featureAniso); featureMinNbKernelsArray.push_back(featureMinNbKernels); int nfeatureMaxNbKernels = (int)((float)featureMaxNbKernels*(1.0f + (initial ? 0.0 : 0.5*ecart)*(2.0f*(float)rand() / (float)RAND_MAX - 1.0f)) + 0.5); if (nfeatureMaxNbKernels < featureMinNbKernels) nfeatureMaxNbKernels = featureMinNbKernels; featureMaxNbKernelsArray.push_back(nfeatureMaxNbKernels); featureSigcosArray.push_back(featureSigcos); featureSigcosvarArray.push_back(featureSigcosvar); featureFrequencyArray.push_back(featureFrequency*(1.0f + (initial ? 0.0 : 0.5*ecart)*(2.0f*(float)rand() / (float)RAND_MAX - 1.0f))); featurePhaseShiftArray.push_back(featurePhaseShift*M_PI*0.5); featureThicknessArray.push_back(featureThickness*(1.0f + (initial ? 0.0 : 0.5*ecart)*(2.0f*(float)rand() / (float)RAND_MAX - 1.0f))); featureCurvatureArray.push_back(featureCurvature); featureOrientationArray.push_back(M_PI * featureOrientation *(1.0f + (initial ? 0.0 : 0.5*ecart)*(2.0f*(float)rand() / (float)RAND_MAX - 1.0f))); //fprintf(fdn, "%06d %g %d %g %g %g %g %g %d %g %g %g %g %g %g %d %g %g %g %d %d %g %g %d %g %g %g %g\n", pptbf_count, jittering, resolution, rotation, rescalex, turbAmplitude0, turbAmplitude1, turbAmplitude2, // windowShape, windowArity, windowLarp, windowNorm, windowSmoothness, windowBlend, windowSigwcell, // featureBombing, featureNorm, featureWinfeatcorrel, featureAniso, featureMinNbKernels, featureMaxNbKernels, featureSigcos, featureSigcosvar, featureFrequency, featurePhaseShift, featureThickness, featureCurvature, featureOrientation); pptbf_count++; initial = false; } fgets(buff1, 1000, fd); fgets(buff2, 1000, fd); fgets(buff3, 1000, fd); pptbf_countf++; } else cont = false; } while (cont); // fclose(fdn); fclose(fd); #endif //////////////// //// Deformation //////////////// //// Parameter 0 //for ( float param_0 = 0.0f; param_0 <= 1.0f; param_0 += 0.25f ) //{ // turbulenceAmplitude0Array.push_back( param_0 ); //} //// Parameter 1 //for ( float param_1 = 0.0f; param_1 <= 1.0f; param_1 += 0.25f ) //{ // turbulenceAmplitude1Array.push_back( param_1 ); //} //// Parameter 2 //for ( float param_2 = 0.0f; param_2 <= 1.0f; param_2 += 0.25f ) //{ // turbulenceAmplitude2Array.push_back( param_2 ); //} ////////////////// //// Point Process ////////////////// //// Tiling type ////tilingTypeArray.resize( 18 ); ////std::iota( tilingTypeArray.begin(), tilingTypeArray.end(), 0 ); ////for ( int tileid = 0; tileid <= 17; tileid++ ) //for ( int tileid = do_tiling; tileid <= do_tiling; tileid++ ) //{ // tilingTypeArray.push_back( tileid ); //} //// Jittering //for ( float jitter = 0.5f; jitter <= 1.0f; jitter += 0.45f ) //{ // jitteringArray.push_back( jitter ); //} //////////////////// //// Model Transform & Deformation //////////////////// //// Resolution //for (int resolution = 50; resolution <= 200; resolution += 50) //{ // modelResolutionArray.push_back(resolution); //} //// Alpha //for (float alpha = 0.f; alpha <= 2.f; alpha += 0.25f) //{ // modelAlphaArray.push_back(alpha * M_PI); //} //// Rescale X //for (float rescalex = 1.0f; rescalex <= 4.f; rescalex += 0.5f) //{ // modelRescalexArray.push_back(rescalex); //} //////////////////// //// WINDOW FUNCTION //////////////////// //// Shape ////for ( int shape = 0; shape <= 3; shape += 1 ) //for ( int shape = 2; shape <= 3; shape += 1 ) //{ // windowShapeArray.push_back( shape ); //} //// Arity ////for ( float windowArity = 2.f; windowArity <= 6.f; windowArity += 1.f ) //for ( float windowArity = 6.f; windowArity <= 6.f; windowArity += 1.f ) //{ // windowArityArray.push_back( windowArity ); //} //// Larp //for ( float windowLarp = 0.f; windowLarp <= 1.f; windowLarp += 0.5f ) //{ // windowLarpArray.push_back( windowLarp ); //} //// Norm ////for ( float windowNorm = 1.f; windowNorm <= 3.f; windowNorm += 1.f ) //for ( float windowNorm = 2.f; windowNorm <= 3.f; windowNorm += 1.f ) //{ // windowNormArray.push_back( windowNorm ); //} //// Smooth //for ( float windowSmooth = 0.f; windowSmooth <= 2.f; windowSmooth += 1.f ) //{ // windowSmoothArray.push_back( windowSmooth ); //} //// Blend ////for ( float windowBlend = 0.f; windowBlend <= 1.f; windowBlend += 0.25f ) //for ( float windowBlend = 1.f; windowBlend <= 1.f; windowBlend += 0.25f ) //{ // windowBlendArray.push_back( windowBlend ); //} //// Sigwcell ////for ( float windowSigwcell = 0.f; windowSigwcell <= 1.f; windowSigwcell += 0.25f ) //for ( float windowSigwcell = 0.1f; windowSigwcell <= 1.f; windowSigwcell += 0.25f ) //{ // windowSigwcellArray.push_back( windowSigwcell ); //} ///////////////////// //// Feature Function ///////////////////// //// Bombing //for ( int bombing = 0; bombing <= 3; bombing += 1 ) //{ // featureBombingArray.push_back( bombing ); //} //// Norm ////for ( float norm = 1.0; norm <= 3.0; norm += 1.0 ) //for ( float norm = 2.0; norm <= 3.0; norm += 1.0 ) //{ // featureNormArray.push_back( norm ); //} //// Winfeatcorrel //for ( float winfeatcorrel = 0.0; winfeatcorrel <= 10.0; winfeatcorrel += 1.0 ) //{ // featureWinfeatcorrelArray.push_back( winfeatcorrel ); //} //// Anisotropy ////for ( float anisotropy = 1.0; anisotropy <= 10.0; anisotropy += 1.0 ) //for ( float anisotropy = 10.f; anisotropy <= 10.0; anisotropy += 1.0 ) //{ // featureAnisoArray.push_back( anisotropy ); //} //// Min/Max number of kernels //for ( int Npmin = 1; Npmin <= 8; Npmin += 4 ) //{ // featureMinNbKernelsArray.push_back( Npmin ); // for ( int Npmax = Npmin; Npmin <= 8; Npmin += 4 ) // { // featureMaxNbKernelsArray.push_back( Npmax ); // } //} //// Sigcos ////for ( float featureSigcos = 0.1f; featureSigcos <= 1.f; featureSigcos += 0.5f ) //for ( float featureSigcos = 1.f; featureSigcos <= 1.f; featureSigcos += 0.5f ) //{ // featureSigcosArray.push_back( featureSigcos ); //} //// Sigcosvar //for ( float featureSigcosvar = 0.1f; featureSigcosvar <= 1.f; featureSigcosvar += 0.5f ) //{ // featureSigcosvarArray.push_back( featureSigcosvar ); //} //// Frequency //for ( int ifreq = 0; ifreq <= 3; ifreq += 1 ) //{ // featureFrequencyArray.push_back( ifreq ); //} //// Phase //for ( float phase = 0.0; phase <= 2.0; phase += 2.0 ) //{ // featurePhaseShiftArray.push_back( phase * M_PI ); //} //// Thickness ////for ( float thickness = 0.1; thickness <= 1.0; thickness += 0.4 ) //for ( float thickness = 0.01f; thickness <= 1.0; thickness += 0.4 ) //{ // featureThicknessArray.push_back( thickness ); //} //// Curvature //for ( float curvature = 0.0; curvature <= 0.4; curvature += 0.2 ) //{ // featureCurvatureArray.push_back( curvature ); //} //// Orientation //for ( float deltaorient = 0.0; deltaorient <= M_PI / 2.0; deltaorient += M_PI / 4.0 ) //{ // featureOrientationArray.push_back( deltaorient ); //} #endif std::vector< std::vector<unsigned char> > similarity(pptbf_count); int pptbf_keep_count = 0; bool *keep = new bool[pptbf_count]; //sprintf(pname, "%s/pptbf_%02d_%02d_%d_%d_%d.txt", pPath, do_serie, do_tiling, do_window, do_feature, do_phase); //sprintf(pname, "%s/pptbf_%02d_%02d_%d_%d_%d.txt", pPath, do_serie, do_tiling, do_window, do_feature, do_phase); //fd = fopen(pname, "w"); //fprintf(fd, "num jittering zoom rotation rescalex turbAmplitude0 turbAmplitude1 turbAmplitude2 windowShape windowArity windowLarp windowNorm windowSmoothness windowBlend windowSigwcell featureBombing featureNorm featureWinfeatcorrel featureAniso featureMinNbKernels featureMaxNbKernels featureSigcos featureSigcosvar featureFrequency featurePhaseShift featureThickness featureCurvature featureOrientation\n"); /////////////////////// // Set common GL states /////////////////////// //setImageWidth( width ); //setImageHeight( height ); setWidth( width ); setHeight( height ); // Set shader program PtShaderProgram* shaderProgram = mMegakernelShaderProgram; shaderProgram->use(); // Set texture(s) // - PRNG glBindTextureUnit( 0/*unit*/, mTexture_P ); // - noise glBindTextureUnit( 1/*unit*/, mTexture_rnd_tab ); // Set sampler(s) // - PRNG glBindSampler( 0/*unit*/, mSampler_PRNG_Noise ); // - noise glBindSampler( 1/*unit*/, mSampler_PRNG_Noise ); // Set image(s) // - PPTBF (output) glBindImageTexture( 0/*unit*/, mPPTBFTexture, 0/*level*/, GL_FALSE/*layered*/, 0/*layer*/, GL_WRITE_ONLY, GL_R32F ); // Set uniform(s) // - PRNG shaderProgram->set( 0, "uPermutationTex" ); // - noise shaderProgram->set( 1, "uNoiseTex" ); // Kernel configuration // - block const int blockSizeX = 8; // TODO: benchmark with 8x8, 16x16 and 32x32 const int blockSizeY = 8; // - grid const GLuint gridSizeX = glm::max( ( width + blockSizeX - 1 ) / blockSizeX, 1 ); const GLuint gridSizeY = glm::max( ( height + blockSizeY - 1 ) / blockSizeY, 1 ); ///////////////////////////////////////// // Sampling the space of PPTBF structures ///////////////////////////////////////// // Global PPTBF counter #ifdef REFINEMENT fprintf(fdn, "%g\n", 1.0 - percent); #endif for (int k = 0; k<pptbf_count; k++) { //// Deformation //int d_0 = 0; //int d_1 = 0; //int d_2 = 0; //// Model Transform //int m_0 = 0; //int m_1 = 0; //int m_2 = 0; //// Point process //int p_0 = 0; //int p_1 = 0; //// Window function //int w_0 = 0; //int w_1 = 0; //int w_2 = 0; //int w_3 = 0; //int w_4 = 0; //int w_5 = 0; //int w_6 = 0; //// Feature function //int f_0 = 0; //int f_1 = 0; //int f_2 = 0; //int f_3 = 0; //int f_4 = 0; //int f_5 = 0; //int f_6 = 0; //int f_7 = 0; //int f_8 = 0; //int f_9 = 0; //int f_10 = 0; //int f_11 = 0; //int f_12 = 0; //std::size_t nbSamples = 1; //// Deformation //nbSamples *= turbulenceAmplitude0Array.size(); //nbSamples *= turbulenceAmplitude1Array.size(); //nbSamples *= turbulenceAmplitude2Array.size(); //// Model Transform //nbSamples *= modelResolutionArray.size(); //nbSamples *= modelAlphaArray.size(); //nbSamples *= modelRescalexArray.size(); //// Point process //nbSamples *= tilingTypeArray.size(); //nbSamples *= jitteringArray.size(); //// Window function //nbSamples *= windowShapeArray.size(); //nbSamples *= windowArityArray.size(); //nbSamples *= windowLarpArray.size(); //nbSamples *= windowNormArray.size(); //nbSamples *= windowSmoothArray.size(); //nbSamples *= windowBlendArray.size(); //nbSamples *= windowSigwcellArray.size(); //// Feature function //nbSamples *= featureBombingArray.size(); //nbSamples *= featureNormArray.size(); //nbSamples *= featureWinfeatcorrelArray.size(); //nbSamples *= featureAnisoArray.size(); //nbSamples *= featureMinNbKernelsArray.size(); //nbSamples *= featureMaxNbKernelsArray.size(); //nbSamples *= featureSigcosArray.size(); //nbSamples *= featureSigcosvarArray.size(); //nbSamples *= featureFrequencyArray.size(); //nbSamples *= featurePhaseShiftArray.size(); //nbSamples *= featureThicknessArray.size(); //nbSamples *= featureCurvatureArray.size(); //nbSamples *= featureOrientationArray.size(); //////////////// // Point Process //////////////// //p_0 = 0; //for ( const auto tilingType : tilingTypeArray ) //{ shaderProgram->set(tilingTypeArray[k], "uPointProcessTilingType" ); //p_1 = 0; //for ( const auto jittering : jitteringArray ) //{ shaderProgram->set(jitteringArray[k], "uPointProcessJitter" ); ////////////////// // Model Transform ////////////////// //m_0 = 0; //for ( const auto modelResolution : modelResolutionArray ) //{ shaderProgram->set(modelResolutionArray[k], "uResolution" ); //m_1 = 0; //for ( const auto modelAlpha : modelAlphaArray ) //{ shaderProgram->set(modelAlphaArray[k], "uRotation" ); //m_2 = 0; //for ( const auto modelRescalex : modelRescalexArray ) //{ shaderProgram->set( modelRescalexArray[k], "uRescaleX" ); ////////////// // Deformation ////////////// //d_0 = 0; //for ( const auto deformation_0 : turbulenceAmplitude0Array ) //{ shaderProgram->set(turbulenceAmplitude0Array[k], "uTurbulenceAmplitude_0" ); //d_1 = 0; //for ( const auto deformation_1 : turbulenceAmplitude1Array ) //{ shaderProgram->set(turbulenceAmplitude1Array[k], "uTurbulenceAmplitude_1" ); //d_2 = 0; //for ( const auto deformation_2 : turbulenceAmplitude2Array ) //{ shaderProgram->set(turbulenceAmplitude2Array[k], "uTurbulenceAmplitude_2" ); ////////////////// // Window Function ////////////////// //w_0 = 0; //for ( const auto windowShape : windowShapeArray ) //{ shaderProgram->set(windowShapeArray[k], "uWindowShape" ); //w_1 = 0; //for ( const auto windowArity : windowArityArray ) //{ shaderProgram->set(windowArityArray[k], "uWindowArity" ); //w_2 = 0; //for ( const auto windowLarp : windowLarpArray ) //{ shaderProgram->set(windowLarpArray[k], "uWindowLarp" ); //w_3 = 0; //for ( const auto windowNorm : windowNormArray ) //{ shaderProgram->set(windowNormArray[k], "uWindowNorm" ); //w_4 = 0; //for ( const auto windowSmooth : windowSmoothArray ) //{ shaderProgram->set(windowSmoothArray[k], "uWindowSmooth" ); //w_5 = 0; //for ( const auto windowBlend : windowBlendArray ) //{ shaderProgram->set(windowBlendArray[k], "uWindowBlend" ); //w_6 = 0; //for ( const auto windowSigwcell : windowSigwcellArray ) //{ shaderProgram->set(windowSigwcellArray[k], "uWindowSigwcell" ); /////////////////// // Feature Function /////////////////// //f_0 = 0; //for ( const auto featureBombing : featureBombingArray ) //{ shaderProgram->set(featureBombingArray[k], "uFeatureBomb" ); //f_1 = 0; //for ( const auto featureNorm : featureNormArray ) //{ shaderProgram->set(featureNormArray[k], "uFeatureNorm" ); //f_2 = 0; //for ( const auto featureWinfeatcorrel : featureWinfeatcorrelArray ) //{ shaderProgram->set(featureWinfeatcorrelArray[k], "uFeatureWinfeatcorrel" ); //f_3 = 0; //for ( const auto featureAniso : featureAnisoArray ) //{ shaderProgram->set(featureAnisoArray[k], "uFeatureAniso" ); //f_4 = 0; //for ( const auto minNbGaborKernels : featureMinNbKernelsArray ) //{ shaderProgram->set(featureMinNbKernelsArray[k], "uFeatureNpmin" ); //f_5 = 0; //for ( const auto maxNbGaborKernels : featureMaxNbKernelsArray ) //{ shaderProgram->set(featureMaxNbKernelsArray[k], "uFeatureNpmax" ); //f_6 = 0; //for ( const auto featureSigcos : featureSigcosArray ) //{ shaderProgram->set(featureSigcosArray[k], "uFeatureSigcos" ); //f_7 = 0; //for ( const auto featureSigcosvar : featureSigcosvarArray ) //{ shaderProgram->set(featureSigcosvarArray[k], "uFeatureSigcosvar" ); //f_8 = 0; //for ( const auto gaborStripesFrequency : featureFrequencyArray ) //{ shaderProgram->set(featureFrequencyArray[k], "uFeatureFreq" ); //f_9 = 0; //for ( const auto featurePhase : featurePhaseShiftArray ) //{ shaderProgram->set(featurePhaseShiftArray[k], "uFeaturePhase" ); //f_10 = 0; //for ( const auto gaborStripesThickness : featureThicknessArray ) //{ shaderProgram->set(featureThicknessArray[k], "uFeatureThickness" ); //f_11 = 0; //for ( const auto gaborStripesCurvature : featureCurvatureArray ) //{ shaderProgram->set(featureCurvatureArray[k], "uFeatureCourbure" ); //f_12 = 0; //for ( const auto gaborStripesOrientation : featureOrientationArray ) //{ shaderProgram->set(featureOrientationArray[k], "uFeatureDeltaorient" ); //---------------------------------------------------------------------------------------------- // FOR NEW code // - labeling shaderProgram->set( /*getNbLabels()*/0, "uNbLabels" ); // -default translation shaderProgram->set( /*getShiftX()*/0.f, "uShiftX" ); shaderProgram->set( /*getShiftY()*/0.f, "uShiftY" ); // - labeling glBindImageTexture( 1/*unit*/, mPPTBFLabelMap, 0/*level*/, GL_FALSE/*layered*/, 0/*layer*/, GL_WRITE_ONLY, GL_R8UI ); // - labeling glBindImageTexture( 2/*unit*/, mPPTBFRandomValueMap, 0/*level*/, GL_FALSE/*layered*/, 0/*layer*/, GL_WRITE_ONLY, GL_R32F ); //---------------------------------------------------------------------------------------------- //--------------------- // Generate PPTBF image //--------------------- std::cout << "generating image: " << ( k + 1 ) << "/" << pptbf_count << std::endl; // Launch mega-kernel glDispatchCompute( gridSizeX, gridSizeY, 1 ); // Synchronization // - make sure writing to image has finished before read glMemoryBarrier( GL_SHADER_IMAGE_ACCESS_BARRIER_BIT ); // pb: wait for nothing? use a boolean if someone need to sample texture glMemoryBarrier( GL_ALL_BARRIER_BITS ); //------------------- // Export PPTBF image //------------------- // Retrieve data on host std::vector< float > f_pptbf( width * height ); #if 1 // - deal with odd texture dimensions glPixelStorei( GL_PACK_ALIGNMENT, 1 ); #endif glGetTextureImage( mPPTBFTexture, 0/*level*/, GL_RED, GL_FLOAT, sizeof( float ) * width * height, f_pptbf.data() ); //------------------- // make approximate histogramm equalization //------------------- float f_avg = 0.0; float f_min = 0.0, f_max = 0.0; int count = 0; for (int i = 0; i < width * height; i++) { #ifdef _WIN32 if (!std::isnan<float>(f_pptbf[i])) #else if (!std::isnan(f_pptbf[i])) #endif { f_avg += f_pptbf[i]; count++; if (i == 0) { f_min = f_avg; f_max = f_avg; } if (f_min > f_pptbf[i]) f_min = f_pptbf[i]; if (f_max < f_pptbf[i]) f_max = f_pptbf[i]; } } f_avg /= (float)(count); //std::cout << "avg=" << f_avg << ", min=" << f_min << ", max=" << f_max << "\n"; //int cmin = 0, cmax = 0; //float f_avgmin[3] = { 0.0, 0.0, 0.0 }, f_avgmax[3] = { 0.0,0.0,0.0 }; //for (int i = 0; i < width * height; i++) //{ // if (!isnan<float>(f_pptbf[i])) // { // if (f_pptbf[i] < f_avg) { f_avgmin[1] += f_pptbf[i]; cmin++; } // else { f_avgmax[1] += f_pptbf[i]; cmax++; } // } //} //f_avgmin[1] /= (float)cmin; f_avgmax[1] /= (float)cmax; //cmin = 0; cmax = 0; //for (int i = 0; i < width * height; i++) //{ // if (!isnan<float>(f_pptbf[i])) // { // if (f_pptbf[i] < f_avg) // { // if (f_pptbf[i] < f_avgmin[1]) { f_avgmin[0] += f_pptbf[i]; cmin++; } // else { f_avgmin[2] += f_pptbf[i]; cmax++; } // } // } //} //f_avgmin[0] /= (float)cmin; f_avgmin[2] /= (float)cmax; //cmin = 0; cmax = 0; //for (int i = 0; i < width * height; i++) //{ // if (!isnan<float>(f_pptbf[i])) // { // if (f_pptbf[i] > f_avg) // { // if (f_pptbf[i] < f_avgmax[1]) { f_avgmax[0] += f_pptbf[i]; cmin++; } // else { f_avgmax[2] += f_pptbf[i]; cmax++; } // } // } //} //f_avgmax[0] /= (float)cmin; f_avgmax[2] /= (float)cmax; const int bins = 100; float histo[bins]; for (int i = 0; i < bins; i++) histo[i] = 0.0f; for (int i = 0; i < width * height; i++) { if (f_pptbf[i] < f_avg) f_pptbf[i] = (f_pptbf[i] - f_min) / (f_avg - f_min)*0.5; else f_pptbf[i] = (f_pptbf[i] - f_avg) / (f_max - f_avg)*0.5+0.5; int iv = (int)((float)(bins)*f_pptbf[i]); if (iv >= bins) iv = bins - 1; histo[iv] += 1.0f / (float)(width * height); //if (f_pptbf[i] < f_avgmin[0]) f_pptbf[i] = (f_pptbf[i] - f_min) / (f_avgmin[0] - f_min)*0.125; //else if (f_pptbf[i] < f_avgmin[1]) f_pptbf[i] = (f_pptbf[i] - f_avgmin[0]) / (f_avgmin[1] - f_avgmin[0])*0.125+0.125; //else if (f_pptbf[i] < f_avgmin[2]) f_pptbf[i] = (f_pptbf[i] - f_avgmin[1]) / (f_avgmin[2] - f_avgmin[1])*0.125 + 0.25; //else if (f_pptbf[i] < f_avg) f_pptbf[i] = (f_pptbf[i] - f_avgmin[2]) / (f_avg - f_avgmin[2])*0.125+0.375; //else if (f_pptbf[i] < f_avgmax[0]) f_pptbf[i] = (f_pptbf[i] - f_avg) / (f_avgmax[0] - f_avg)*0.125 + 0.5; //else if (f_pptbf[i] < f_avgmax[1]) f_pptbf[i] = (f_pptbf[i] - f_avgmax[0]) / (f_avgmax[1] - f_avgmax[0])*0.125 + 0.625; //else if (f_pptbf[i] < f_avgmax[2]) f_pptbf[i] = (f_pptbf[i] - f_avgmax[1]) / (f_avgmax[2] - f_avgmax[1])*0.125 + 0.75; //else f_pptbf[i] = (f_pptbf[i] - f_avgmax[2]) / (f_max - f_avgmax[2])*0.125 + 0.875; } int i; float sum = 0.0; for (i = 0; i < bins && sum < percent; i++) sum += histo[i]; //if (i == bins) return vmax; float ratio = (percent - (sum - histo[i])) / histo[i]; //float ratio = 0.5f; //printf("compute Thresh bin =%d, sum=%g, percent=%g\n", i, sum, percent); float rangea = ((float)(i - 1) / (float)bins + ratio / (float)bins); keep[k] = true; #ifdef REFINEMENT for (int i = 0; i < width * height; i++) { if (f_pptbf[i] > rangea) f_pptbf[i] = 1.0; else f_pptbf[i] = 0.0; } #else for (int i = 0; i < width-1; i+=4) for (int j = 0; j < height-1; j+=4) similarity[k].push_back((unsigned char)(255.0/4.0*(f_pptbf[i+j*width]+ f_pptbf[i+1 + j*width]+ f_pptbf[i + (j+1)*width]+ f_pptbf[i+1 + (j+1)*width]))); int r; for (r = 0; r < k && keep[k]; r++) { if (keep[r]) { float mse = 0.0; for (int i = 0; i < width*height / 16; i++) mse += ((float)similarity[k][i] - (float)similarity[r][i])*((float)similarity[k][i] - (float)similarity[r][i]); if (sqrt(mse) < (float)(width*height) / 16.0 * KEEP_ERROR) keep[k] = false; //printf("error %d - %d is %g\n", k, r, sqrt(mse)); } } #endif if (keep[k]) { // Deformation turbAmplitude0 = turbulenceAmplitude0Array[k]; turbAmplitude1 = turbulenceAmplitude1Array[k]; turbAmplitude2 = turbulenceAmplitude2Array[k]; // Model Transform resolution = modelResolutionArray[k]; rotation = modelAlphaArray[k] / M_PI; rescalex = modelRescalexArray[k]; // Point process do_tiling = tilingTypeArray[k]; jittering = jitteringArray[k]; // Window function windowShape = windowShapeArray[k]; windowArity = windowArityArray[k]; windowLarp = windowLarpArray[k]; windowNorm = windowNormArray[k]; windowSmoothness = windowSmoothArray[k]; windowBlend = windowBlendArray[k]; windowSigwcell = windowSigwcellArray[k]; // Feature function featureBombing = featureBombingArray[k]; featureNorm = featureNormArray[k]; featureWinfeatcorrel = featureWinfeatcorrelArray[k]; featureAniso = featureAnisoArray[k]; featureMinNbKernels = featureMinNbKernelsArray[k]; featureMaxNbKernels = featureMaxNbKernelsArray[k]; featureSigcos = featureSigcosArray[k]; featureSigcosvar = featureSigcosvarArray[k]; featureFrequency = featureFrequencyArray[k]; featurePhaseShift = featurePhaseShiftArray[k]/M_PI/0.5; featureThickness = featureThicknessArray[k]; featureCurvature = featureCurvatureArray[k]; featureOrientation = featureOrientationArray[k]/M_PI; #ifdef REFINEMENT fprintf(fdn, "%02d %02d %d %d %d\n", 0, do_tiling, 0, 0, 0); fprintf(fdn, "%06d %g %d %d\n", pptbf_keep_count, 0.0, 0, 0); fprintf(fdn, "%06d %g %d %g %g %g %g %g %d %g %g %g %g %g %g %d %g %g %g %d %d %g %g %d %g %g %g %g\n", pptbf_keep_count, jittering, resolution, rotation, rescalex, turbAmplitude0, turbAmplitude1, turbAmplitude2, windowShape, windowArity, windowLarp, windowNorm, windowSmoothness, windowBlend, windowSigwcell, featureBombing, featureNorm, featureWinfeatcorrel, featureAniso, featureMinNbKernels, featureMaxNbKernels, featureSigcos, featureSigcosvar, featureFrequency, featurePhaseShift, featureThickness, featureCurvature, featureOrientation); #else fprintf(fdn, "%06d %g %d %g %g %g %g %g %d %g %g %g %g %g %g %d %g %g %g %d %d %g %g %d %g %g %g %g\n", pptbf_keep_count, jittering, resolution, rotation, rescalex, turbAmplitude0, turbAmplitude1, turbAmplitude2, windowShape, windowArity, windowLarp, windowNorm, windowSmoothness, windowBlend, windowSigwcell, featureBombing, featureNorm, featureWinfeatcorrel, featureAniso, featureMinNbKernels, featureMaxNbKernels, featureSigcos, featureSigcosvar, featureFrequency, featurePhaseShift, featureThickness, featureCurvature, featureOrientation); #endif pptbf_keep_count++; fflush(fd); } // else printf("erased %d as it looks like %d\n", k, r-1); if (keep[k]) { // Convert data (float to unsigned char) // TODO: maybe use for_each with a lambda doing the "cast" directly instead? std::transform(f_pptbf.begin(), f_pptbf.end(), f_pptbf.begin(), std::bind(std::multiplies< float >(), std::placeholders::_1, 255.f)); std::vector< unsigned char > u_pptbf(f_pptbf.begin(), f_pptbf.end()); // Save data in image //const std::string pptbfName = std::string( "pptbf_" )/*name*/ + std::to_string( i ); char numbuff[100]; #ifdef REFINEMENT sprintf(numbuff, "_%d_%06d", descriptor,pptbf_keep_count - 1); #else sprintf(numbuff, "_%02d_%02d_%d_%d_%d_%06d", do_serie, do_tiling, do_window, do_feature, do_phase, pptbf_keep_count-1); #endif const std::string pptbfName = std::string("pptbf")/*name*/ + std::string(numbuff); //+ std::string( "_D_" ) + std::to_string( d_0 ) + std::string( "_" ) + std::to_string( d_1 ) + std::string( "_" ) + std::to_string( d_2 ) //+ std::string( "_M_" ) + std::to_string( m_0 ) + std::string( "_" ) + std::to_string( m_1 ) + std::string( "_" ) + std::to_string( m_2 ) //+ std::string( "_P_" ) + std::to_string( p_0 ) + std::string( "_" ) + std::to_string( p_1 ) //+ std::string( "_W_" ) + std::to_string( w_0 ) + std::string( "_" ) + std::to_string( w_1 ) + std::string( "_" ) + std::to_string( w_2 ) // + std::string( "_" ) + std::to_string( w_3 ) + std::string( "_" ) + std::to_string( w_4 ) + std::string( "_" ) + std::to_string( w_5 ) // + std::string( "_" ) + std::to_string( w_6 ) //+ std::string( "_F_" ) + std::to_string( f_0 ) + std::string( "_" ) + std::to_string( f_1 ) + std::string( "_" ) + std::to_string( f_2 ) // + std::string( "_" ) + std::to_string( f_3 ) + std::string( "_" ) + std::to_string( f_4 ) + std::string( "_" ) + std::to_string( f_5 ) // + std::string( "_" ) + std::to_string( f_6 ) + std::string( "_" ) + std::to_string( f_7 ) + std::string( "_" ) + std::to_string( f_8 ) // + std::string( "_" ) + std::to_string( f_9 ) + std::string( "_" ) + std::to_string( f_10 ) + std::string( "_" ) + std::to_string( f_11 ) // + std::string( "_" ) + std::to_string( f_12 ); const std::string pptbfFilename = databasePath + pptbfName + std::string(".png"); PtImageHelper::saveImage(pptbfFilename.c_str(), width, height, 1/*nb channels*/, u_pptbf.data()); } // Update counter //i++; /*} } } } } } } } } } } } } w_6++; } w_5++; } w_4++; } w_3++; } w_2++; } w_1++; } w_0++; } p_1++; } p_0++; } m_2++; } m_1++; } m_0++; } d_2++; } d_1++; } d_0++; } */ } fclose(fdn); // Reset GL state(s) // - Unset shader program PtShaderProgram::unuse(); // LOG info std::cout << "Finished..." << pptbf_count << std::endl; } /****************************************************************************** * sampleParameterSpace ******************************************************************************/ void PtGraphicsPPTBF::sampleParameterSpace( const unsigned int pWidth, const unsigned int pHeight, const char* pPath, const char* pImageName, // method parameters const int pDescriptor, const int pKEEPNBEST, const int pNR, const float pDeltaAlpha, const float pFactResol, const float pFactRescaleX, const float pEcart, const float pPercent, // external data std::vector< float >& mPptbfCandidateThresholds, std::vector< float >& mPptbfCandidateMinValues, std::vector< float >& mPptbfCandidateMaxValues, std::vector< float >& mPptbfCandidateMeanValues, std::vector< bool >& mSelectedNNCandidates, // PPTBF // - Point Process std::vector< int >& tilingTypeArray, std::vector< float >& jitteringArray, // - Transform std::vector< int >& modelResolutionArray, std::vector< float >& modelAlphaArray, std::vector< float >& modelRescalexArray, // - Turbulence std::vector< float >& turbulenceAmplitude0Array, std::vector< float >& turbulenceAmplitude1Array, std::vector< float >& turbulenceAmplitude2Array, std::vector< std::vector< float > >& turbAmp, // - Window std::vector< int >& windowShapeArray, std::vector< float >& windowArityArray, std::vector< float >& windowLarpArray, std::vector< float >& windowNormArray, std::vector< float >& windowSmoothArray, std::vector< float >& windowBlendArray, std::vector< float >& windowSigwcellArray, // - Feature std::vector< int >& featureBombingArray, std::vector< float >& featureNormArray, std::vector< float >& featureWinfeatcorrelArray, std::vector< float >& featureAnisoArray, std::vector< int >& featureMinNbKernelsArray, std::vector< int >& featureMaxNbKernelsArray, std::vector< float >& featureSigcosArray, std::vector< float >& featureSigcosvarArray, std::vector< int >& featureFrequencyArray, std::vector< float >& featurePhaseShiftArray, std::vector< float >& featureThicknessArray, std::vector< float >& featureCurvatureArray, std::vector< float >& featureOrientationArray, // save bank ID std::vector< int >& featureBankIDs ) { assert( pWidth != 0 && pHeight != 0 ); //----------------------------------------------------------------------------------------- featureBankIDs.clear(); mSelectedNNCandidates.clear(); mPptbfCandidateThresholds.clear(); mPptbfCandidateMinValues.clear(); mPptbfCandidateMaxValues.clear(); mPptbfCandidateMeanValues.clear(); // PPTBF // - point process tilingTypeArray.clear(), jitteringArray.clear(); // - transform modelResolutionArray.clear(); modelAlphaArray.clear(); modelRescalexArray.clear(); // - turbulence turbulenceAmplitude0Array.clear(); turbulenceAmplitude1Array.clear(); turbulenceAmplitude2Array.clear(); turbAmp.clear(); // - window windowShapeArray.clear(); windowArityArray.clear(); windowLarpArray.clear(); windowNormArray.clear(); windowSmoothArray.clear(); windowBlendArray.clear(); windowSigwcellArray.clear(); // - feature featureBombingArray.clear(); featureNormArray.clear(); featureWinfeatcorrelArray.clear(); featureAnisoArray.clear(); featureMinNbKernelsArray.clear(); featureMaxNbKernelsArray.clear(); featureSigcosArray.clear(); featureSigcosvarArray.clear(); featureFrequencyArray.clear(); featurePhaseShiftArray.clear(); featureThicknessArray.clear(); featureCurvatureArray.clear(); featureOrientationArray.clear(); //----------------------------------------------------------------------------------------- unsigned int pSerieID; // LOG info std::cout << "\nPPTBF Database generation..." << std::endl; std::cout << "START..." << std::endl; const int width = pWidth; const int height = pHeight; // Resize graphics resources onSizeModified(width, height); //const std::string databasePath = PtEnvironment::mDataPath + std::string( "/BDDStructure/Test/" ); const std::string databasePath = pPath; // Deformation //std::vector< float > turbulenceAmplitude0Array; //std::vector< float > turbulenceAmplitude1Array; //std::vector< float > turbulenceAmplitude2Array; // Model Transform //std::vector< int > modelResolutionArray; //std::vector< float > modelAlphaArray; //std::vector< float > modelRescalexArray; // Point process //std::vector< int > tilingTypeArray; //std::vector< float > jitteringArray; // Window function //std::vector< int > windowShapeArray; //std::vector< float > windowArityArray; //std::vector< float > windowLarpArray; //std::vector< float > windowNormArray; //std::vector< float > windowSmoothArray; //std::vector< float > windowBlendArray; //std::vector< float > windowSigwcellArray; // Feature function //std::vector< int > featureBombingArray; //std::vector< float > featureNormArray; //std::vector< float > featureWinfeatcorrelArray; //std::vector< float > featureAnisoArray; //std::vector< int > featureMinNbKernelsArray; //std::vector< int > featureMaxNbKernelsArray; //std::vector< float > featureSigcosArray; //std::vector< float > featureSigcosvarArray; //std::vector< int > featureFrequencyArray; //std::vector< float > featurePhaseShiftArray; //std::vector< float > featureThicknessArray; //std::vector< float > featureCurvatureArray; //std::vector< float > featureOrientationArray; /////////////////////////////////////////// // USER Experiment // - sampling the space of PPTBF structures /////////////////////////////////////////// const int descriptor = pDescriptor; // default: 1 const int KEEPNBEST = pKEEPNBEST; // default: 5 const int NR = pNR; // default: 10 float deltaalpha = pDeltaAlpha; // default: 0.0 and 0.5 = pi/2 float factresol = pFactResol; // default: 1.0 float factrescalex = pFactRescaleX; // default: 1.0 float ecart = pEcart; // default: 0.5 //char *exname = "TexturesCom_Asphalt11_2x2_1K_seg_scrop_80"; //char *exname = "TexturesCom_Pavement_CobblestoneForest01_4x4_1K_albedo_seg_scrop"; //char *exname = "20181215_153153_seg_scrop_450"; std::string imageName = std::string( pImageName ); const char* exname = imageName.c_str(); const int SS = 400; char pname[128]; int pptbf_count = 0; float percent = pPercent; // default 0.2 int do_serie = 0; int do_tiling = 0; int do_window = 0; int do_feature = 0; int do_phase = 0; float jittering, wjittering, fjittering; int resolution, wresolution, fresolution; float rotation, wrotation, frotation; float rescalex, wrescalex, frescalex; float turbAmplitude0, turbAmplitude1, turbAmplitude2; float wturbAmplitude0, wturbAmplitude1, wturbAmplitude2; float fturbAmplitude0, fturbAmplitude1, fturbAmplitude2; int windowShape = do_window, wwindowShape, fwindowShape; float windowArity = 10.0, wwindowArity, fwindowArity; float windowLarp = 0.0, wwindowLarp, fwindowLarp; float windowNorm = 2.0, wwindowNorm, fwindowNorm; float windowSmoothness = 0.0, wwindowSmoothness, fwindowSmoothness; float windowBlend = 1.0, wwindowBlend, fwindowBlend; float windowSigwcell = 0.7, wwindowSigwcell, fwindowSigwcell; int featureBombing = 0, wfeatureBombing, ffeatureBombing; float featureNorm = 2.0, wfeatureNorm, ffeatureNorm; float featureWinfeatcorrel = 0.0, wfeatureWinfeatcorrel, ffeatureWinfeatcorrel; float featureAniso = 0.0, wfeatureAniso, ffeatureAniso; int featureMinNbKernels = 0, featureMaxNbKernels = 0; int wfeatureMinNbKernels = 0, wfeatureMaxNbKernels = 0; int ffeatureMinNbKernels = 0, ffeatureMaxNbKernels = 0; float featureSigcos = 1.0, wfeatureSigcos, ffeatureSigcos; float featureSigcosvar = 0.2, wfeatureSigcosvar, ffeatureSigcosvar; int featureFrequency = 0, wfeatureFrequency, ffeatureFrequency; float featurePhaseShift = (float)do_phase, wfeaturePhaseShift, ffeaturePhaseShift; float featureThickness = 1.0, wfeatureThickness, ffeatureThickness; float featureCurvature = 0.0, wfeatureCurvature, ffeatureCurvature; float featureOrientation = 0.0, wfeatureOrientation, ffeatureOrientation; sprintf(pname, "%s/pptbf_matching_rnd_%d.txt", pPath, descriptor); FILE *fdn = fopen(pname, "w"); int pptbf_countf = 0; sprintf(pname, "%s/%s_best_pptbfparams_%d.txt", pPath, exname, descriptor); FILE *fd = fopen(pname, "r"); //sprintf(pname, "%s/pptbf_%02d_%02d_%d_%d_%d.txt", pPath, do_serie, do_tiling, do_window, do_feature, do_phase); //FILE *fdn = fopen(pname, "w"); //fprintf(fdn, "num jittering zoom rotation rescalex turbAmplitude0 turbAmplitude1 turbAmplitude2 windowShape windowArity windowLarp windowNorm windowSmoothness windowBlend windowSigwcell featureBombing featureNorm featureWinfeatcorrel featureAniso featureMinNbKernels featureMaxNbKernels featureSigcos featureSigcosvar featureFrequency featurePhaseShift featureThickness featureCurvature featureOrientation\n"); char buff1[2048], buff2[2048], buff3[2048]; int num; fgets(buff1, 1000, fd); sscanf(buff1, "%g", &percent); percent = 1.0 - percent; fgets(buff1, 1000, fd); fgets(buff2, 1000, fd); fgets(buff3, 1000, fd); bool cont = true; do { sscanf(buff1, "%02d %02d %d %d %d", &do_serie, &do_tiling, &do_window, &do_feature, &do_phase); sscanf(buff3, "%d %g %d %g %g %g %g %g %d %g %g %g %g %g %g %d %g %g %g %d %d %g %g %d %g %g %g %g\n", &num, &jittering, &resolution, &rotation, &rescalex, &turbAmplitude0, &turbAmplitude1, &turbAmplitude2, &windowShape, &windowArity, &windowLarp, &windowNorm, &windowSmoothness, &windowBlend, &windowSigwcell, &featureBombing, &featureNorm, &featureWinfeatcorrel, &featureAniso, &featureMinNbKernels, &featureMaxNbKernels, &featureSigcos, &featureSigcosvar, &featureFrequency, &featurePhaseShift, &featureThickness, &featureCurvature, &featureOrientation); if (pptbf_countf < KEEPNBEST) { cont = true; bool initial = true; for (int iresolution = 0; iresolution < NR; iresolution++) //for (int iresolution = 0; iresolution <= 0; iresolution++) { int nresolution = (int)(factresol*(double)resolution*(1.0f + (initial ? 0.0 : 0.25*ecart)*(2.0f*(float)rand() / (float)RAND_MAX - 1.0f))); float zoom = (float)SS / (float)nresolution; float njittering = jittering*(1.0f + (initial ? 0.0 : ecart)*(2.0f*(float)rand() / (float)RAND_MAX - 1.0f)); if (iresolution >= NR / 2 && !initial) njittering = (float)rand() / (float)RAND_MAX; if (njittering >= 1.0) njittering = 0.99; float nrescalex = factrescalex*rescalex*(1.0f + (initial ? 0.0 : 0.5*ecart)*(2.0f*(float)rand() / (float)RAND_MAX - 1.0f)); float turbAmplitude0A[] = { 0.0, 0.06, 0.05, 0.03, 0.06, 0.05, 0.02 }; float turbAmplitude1A[] = { 0.0, 0.05, 0.5, 0.8, 0.05, 0.5, 0.5 }; float turbAmplitude2A[] = { 1.0, 1.0, 1.0, 1.0, 2.0, 2.0, 4.0 }; float nturbAmplitude0 = turbAmplitude0*(1.0f + (initial ? 0.0 : 0.5*ecart)*(2.0f*(float)rand() / (float)RAND_MAX - 1.0f)); float nturbAmplitude1 = turbAmplitude1*(1.0f + (initial ? 0.0 : 0.5*ecart)*(2.0f*(float)rand() / (float)RAND_MAX - 1.0f)); float nturbAmplitude2 = turbAmplitude2*(1.0f + (initial ? 0.0 : 0.5*ecart)*(2.0f*(float)rand() / (float)RAND_MAX - 1.0f)); if (iresolution >= NR / 2 && !initial) nturbAmplitude0 = turbAmplitude0A[(iresolution - 1) % 6+1]* (1.0+0.2*ecart*(2.0f*(float)rand() / (float)RAND_MAX - 1.0f))* (float)nresolution / (50.0 / 1.0); if (iresolution >= NR / 2 && !initial) nturbAmplitude1 = turbAmplitude1A[(iresolution - 1) % 6+1] * (1.0 + 0.2*ecart*(2.0f*(float)rand() / (float)RAND_MAX - 1.0f)); if (iresolution >= NR / 2 && !initial) nturbAmplitude2 = turbAmplitude2A[(iresolution - 1) % 6+1] * (1.0 + 0.2*ecart*(2.0f*(float)rand() / (float)RAND_MAX - 1.0f)); // Deformation turbulenceAmplitude0Array.push_back(nturbAmplitude0); turbulenceAmplitude1Array.push_back(nturbAmplitude1); turbulenceAmplitude2Array.push_back(nturbAmplitude2); // Model Transform modelResolutionArray.push_back(nresolution); modelAlphaArray.push_back((rotation+ deltaalpha) * M_PI); modelRescalexArray.push_back(nrescalex); // Point process tilingTypeArray.push_back(do_tiling); jitteringArray.push_back(njittering); // Window function float nwindowArity= windowArity*(1.0f + (initial ? 0.0 : 0.5*ecart)*(2.0f*(float)rand() / (float)RAND_MAX - 1.0f)); if (nwindowArity <= 3.0) nwindowArity = 3.0; nwindowArity = floor(nwindowArity); windowShapeArray.push_back(windowShape); windowArityArray.push_back(windowArity); windowLarpArray.push_back(windowLarp*(1.0f + (initial ? 0.0 : 0.2*ecart)*(2.0f*(float)rand() / (float)RAND_MAX - 1.0f))); windowNormArray.push_back(windowNorm); windowSmoothArray.push_back(windowSmoothness*(1.0f + (initial ? 0.0 : 0.2*ecart)*(2.0f*(float)rand() / (float)RAND_MAX - 1.0f))); windowBlendArray.push_back(windowBlend); windowSigwcellArray.push_back(windowSigwcell); // Feature function featureBombingArray.push_back(featureBombing); featureNormArray.push_back(featureNorm); featureWinfeatcorrelArray.push_back(featureWinfeatcorrel*(1.0f + (initial ? 0.0 : 0.5*ecart)*(2.0f*(float)rand() / (float)RAND_MAX - 1.0f))); featureAnisoArray.push_back(featureAniso); featureMinNbKernelsArray.push_back(featureMinNbKernels); int nfeatureMaxNbKernels = (int)((float)featureMaxNbKernels*(1.0f + (initial ? 0.0 : 0.5*ecart)*(2.0f*(float)rand() / (float)RAND_MAX - 1.0f)) + 0.5); if (nfeatureMaxNbKernels < featureMinNbKernels) nfeatureMaxNbKernels = featureMinNbKernels; featureMaxNbKernelsArray.push_back(nfeatureMaxNbKernels); featureSigcosArray.push_back(featureSigcos); featureSigcosvarArray.push_back(featureSigcosvar); featureFrequencyArray.push_back(featureFrequency*(1.0f + (initial ? 0.0 : 0.5*ecart)*(2.0f*(float)rand() / (float)RAND_MAX - 1.0f))); featurePhaseShiftArray.push_back(featurePhaseShift*M_PI*0.5); featureThicknessArray.push_back(featureThickness*(1.0f + (initial ? 0.0 : 0.5*ecart)*(2.0f*(float)rand() / (float)RAND_MAX - 1.0f))); featureCurvatureArray.push_back(featureCurvature); featureOrientationArray.push_back(M_PI * featureOrientation *(1.0f + (initial ? 0.0 : 0.5*ecart)*(2.0f*(float)rand() / (float)RAND_MAX - 1.0f))); //fprintf(fdn, "%06d %g %d %g %g %g %g %g %d %g %g %g %g %g %g %d %g %g %g %d %d %g %g %d %g %g %g %g\n", pptbf_count, jittering, resolution, rotation, rescalex, turbAmplitude0, turbAmplitude1, turbAmplitude2, // windowShape, windowArity, windowLarp, windowNorm, windowSmoothness, windowBlend, windowSigwcell, // featureBombing, featureNorm, featureWinfeatcorrel, featureAniso, featureMinNbKernels, featureMaxNbKernels, featureSigcos, featureSigcosvar, featureFrequency, featurePhaseShift, featureThickness, featureCurvature, featureOrientation); pptbf_count++; initial = false; // Keep track of feature bank ID featureBankIDs.push_back( do_serie ); } fgets( buff1, 1000, fd ); fgets( buff2, 1000, fd ); fgets( buff3, 1000, fd ); pptbf_countf++; } else { cont = false; } } while ( cont ); // fclose(fdn); fclose(fd); std::vector< std::vector< unsigned char > > similarity( pptbf_count ); int pptbf_keep_count = 0; bool* keep = new bool[ pptbf_count ]; //sprintf(pname, "%s/pptbf_%02d_%02d_%d_%d_%d.txt", pPath, do_serie, do_tiling, do_window, do_feature, do_phase); //sprintf(pname, "%s/pptbf_%02d_%02d_%d_%d_%d.txt", pPath, do_serie, do_tiling, do_window, do_feature, do_phase); //fd = fopen(pname, "w"); //fprintf(fd, "num jittering zoom rotation rescalex turbAmplitude0 turbAmplitude1 turbAmplitude2 windowShape windowArity windowLarp windowNorm windowSmoothness windowBlend windowSigwcell featureBombing featureNorm featureWinfeatcorrel featureAniso featureMinNbKernels featureMaxNbKernels featureSigcos featureSigcosvar featureFrequency featurePhaseShift featureThickness featureCurvature featureOrientation\n"); /////////////////////// // Set common GL states /////////////////////// //setImageWidth( width ); //setImageHeight( height ); setWidth( width ); setHeight( height ); // Set shader program PtShaderProgram* shaderProgram = mMegakernelShaderProgram; shaderProgram->use(); // Set texture(s) // - PRNG glBindTextureUnit( 0/*unit*/, mTexture_P ); // - noise glBindTextureUnit( 1/*unit*/, mTexture_rnd_tab ); // Set sampler(s) // - PRNG glBindSampler( 0/*unit*/, mSampler_PRNG_Noise ); // - noise glBindSampler( 1/*unit*/, mSampler_PRNG_Noise ); // Set image(s) // - PPTBF (output) glBindImageTexture( 0/*unit*/, mPPTBFTexture, 0/*level*/, GL_FALSE/*layered*/, 0/*layer*/, GL_WRITE_ONLY, GL_R32F ); // Set uniform(s) // - PRNG shaderProgram->set( 0, "uPermutationTex" ); // - noise shaderProgram->set( 1, "uNoiseTex" ); // Kernel configuration // - block const int blockSizeX = 8; // TODO: benchmark with 8x8, 16x16 and 32x32 const int blockSizeY = 8; // - grid const GLuint gridSizeX = glm::max( ( width + blockSizeX - 1 ) / blockSizeX, 1 ); const GLuint gridSizeY = glm::max( ( height + blockSizeY - 1 ) / blockSizeY, 1 ); ///////////////////////////////////////// // Sampling the space of PPTBF structures ///////////////////////////////////////// // Global PPTBF counter fprintf(fdn, "%g\n", 1.0 - percent); for (int k = 0; k<pptbf_count; k++) { //////////////// // Point Process //////////////// //p_0 = 0; //for ( const auto tilingType : tilingTypeArray ) //{ shaderProgram->set(tilingTypeArray[k], "uPointProcessTilingType" ); //p_1 = 0; //for ( const auto jittering : jitteringArray ) //{ shaderProgram->set(jitteringArray[k], "uPointProcessJitter" ); ////////////////// // Model Transform ////////////////// //m_0 = 0; //for ( const auto modelResolution : modelResolutionArray ) //{ shaderProgram->set(modelResolutionArray[k], "uResolution" ); //m_1 = 0; //for ( const auto modelAlpha : modelAlphaArray ) //{ shaderProgram->set(modelAlphaArray[k], "uRotation" ); //m_2 = 0; //for ( const auto modelRescalex : modelRescalexArray ) //{ shaderProgram->set( modelRescalexArray[k], "uRescaleX" ); ////////////// // Deformation ////////////// //d_0 = 0; //for ( const auto deformation_0 : turbulenceAmplitude0Array ) //{ shaderProgram->set(turbulenceAmplitude0Array[k], "uTurbulenceAmplitude_0" ); //d_1 = 0; //for ( const auto deformation_1 : turbulenceAmplitude1Array ) //{ shaderProgram->set(turbulenceAmplitude1Array[k], "uTurbulenceAmplitude_1" ); //d_2 = 0; //for ( const auto deformation_2 : turbulenceAmplitude2Array ) //{ shaderProgram->set(turbulenceAmplitude2Array[k], "uTurbulenceAmplitude_2" ); ////////////////// // Window Function ////////////////// //w_0 = 0; //for ( const auto windowShape : windowShapeArray ) //{ shaderProgram->set(windowShapeArray[k], "uWindowShape" ); //w_1 = 0; //for ( const auto windowArity : windowArityArray ) //{ shaderProgram->set(windowArityArray[k], "uWindowArity" ); //w_2 = 0; //for ( const auto windowLarp : windowLarpArray ) //{ shaderProgram->set(windowLarpArray[k], "uWindowLarp" ); //w_3 = 0; //for ( const auto windowNorm : windowNormArray ) //{ shaderProgram->set(windowNormArray[k], "uWindowNorm" ); //w_4 = 0; //for ( const auto windowSmooth : windowSmoothArray ) //{ shaderProgram->set(windowSmoothArray[k], "uWindowSmooth" ); //w_5 = 0; //for ( const auto windowBlend : windowBlendArray ) //{ shaderProgram->set(windowBlendArray[k], "uWindowBlend" ); //w_6 = 0; //for ( const auto windowSigwcell : windowSigwcellArray ) //{ shaderProgram->set(windowSigwcellArray[k], "uWindowSigwcell" ); /////////////////// // Feature Function /////////////////// //f_0 = 0; //for ( const auto featureBombing : featureBombingArray ) //{ shaderProgram->set(featureBombingArray[k], "uFeatureBomb" ); //f_1 = 0; //for ( const auto featureNorm : featureNormArray ) //{ shaderProgram->set(featureNormArray[k], "uFeatureNorm" ); //f_2 = 0; //for ( const auto featureWinfeatcorrel : featureWinfeatcorrelArray ) //{ shaderProgram->set(featureWinfeatcorrelArray[k], "uFeatureWinfeatcorrel" ); //f_3 = 0; //for ( const auto featureAniso : featureAnisoArray ) //{ shaderProgram->set(featureAnisoArray[k], "uFeatureAniso" ); //f_4 = 0; //for ( const auto minNbGaborKernels : featureMinNbKernelsArray ) //{ shaderProgram->set(featureMinNbKernelsArray[k], "uFeatureNpmin" ); //f_5 = 0; //for ( const auto maxNbGaborKernels : featureMaxNbKernelsArray ) //{ shaderProgram->set(featureMaxNbKernelsArray[k], "uFeatureNpmax" ); //f_6 = 0; //for ( const auto featureSigcos : featureSigcosArray ) //{ shaderProgram->set(featureSigcosArray[k], "uFeatureSigcos" ); //f_7 = 0; //for ( const auto featureSigcosvar : featureSigcosvarArray ) //{ shaderProgram->set(featureSigcosvarArray[k], "uFeatureSigcosvar" ); //f_8 = 0; //for ( const auto gaborStripesFrequency : featureFrequencyArray ) //{ shaderProgram->set(featureFrequencyArray[k], "uFeatureFreq" ); //f_9 = 0; //for ( const auto featurePhase : featurePhaseShiftArray ) //{ shaderProgram->set(featurePhaseShiftArray[k], "uFeaturePhase" ); //f_10 = 0; //for ( const auto gaborStripesThickness : featureThicknessArray ) //{ shaderProgram->set(featureThicknessArray[k], "uFeatureThickness" ); //f_11 = 0; //for ( const auto gaborStripesCurvature : featureCurvatureArray ) //{ shaderProgram->set(featureCurvatureArray[k], "uFeatureCourbure" ); //f_12 = 0; //for ( const auto gaborStripesOrientation : featureOrientationArray ) //{ shaderProgram->set(featureOrientationArray[k], "uFeatureDeltaorient" ); //---------------------------------------------------------------------------------------------- // FOR NEW code // - labeling shaderProgram->set( /*getNbLabels()*/0, "uNbLabels" ); // -default translation shaderProgram->set( /*getShiftX()*/0.f, "uShiftX" ); shaderProgram->set( /*getShiftY()*/0.f, "uShiftY" ); // - labeling glBindImageTexture( 1/*unit*/, mPPTBFLabelMap, 0/*level*/, GL_FALSE/*layered*/, 0/*layer*/, GL_WRITE_ONLY, GL_R8UI ); // - labeling glBindImageTexture( 2/*unit*/, mPPTBFRandomValueMap, 0/*level*/, GL_FALSE/*layered*/, 0/*layer*/, GL_WRITE_ONLY, GL_R32F ); //---------------------------------------------------------------------------------------------- //--------------------- // Generate PPTBF image //--------------------- std::cout << "generating image: " << ( k + 1 ) << "/" << pptbf_count << std::endl; // Launch mega-kernel glDispatchCompute( gridSizeX, gridSizeY, 1 ); // Synchronization // - make sure writing to image has finished before read glMemoryBarrier( GL_SHADER_IMAGE_ACCESS_BARRIER_BIT ); // pb: wait for nothing? use a boolean if someone need to sample texture glMemoryBarrier( GL_ALL_BARRIER_BITS ); //------------------- // Export PPTBF image //------------------- // Retrieve data on host std::vector< float > f_pptbf( width * height ); #if 1 // - deal with odd texture dimensions glPixelStorei( GL_PACK_ALIGNMENT, 1 ); #endif glGetTextureImage( mPPTBFTexture, 0/*level*/, GL_RED, GL_FLOAT, sizeof( float ) * width * height, f_pptbf.data() ); //------------------- // make approximate histogramm equalization //------------------- float f_avg = 0.0; float f_min = 0.0, f_max = 0.0; int count = 0; for (int i = 0; i < width * height; i++) { #ifdef _WIN32 if (!isnan<float>(f_pptbf[i])) #else if (!isnan(f_pptbf[i])) #endif { f_avg += f_pptbf[i]; count++; if (i == 0) { f_min = f_avg; f_max = f_avg; } if (f_min > f_pptbf[i]) f_min = f_pptbf[i]; if (f_max < f_pptbf[i]) f_max = f_pptbf[i]; } } f_avg /= (float)(count); //std::cout << "avg=" << f_avg << ", min=" << f_min << ", max=" << f_max << "\n"; //int cmin = 0, cmax = 0; //float f_avgmin[3] = { 0.0, 0.0, 0.0 }, f_avgmax[3] = { 0.0,0.0,0.0 }; //for (int i = 0; i < width * height; i++) //{ // if (!isnan<float>(f_pptbf[i])) // { // if (f_pptbf[i] < f_avg) { f_avgmin[1] += f_pptbf[i]; cmin++; } // else { f_avgmax[1] += f_pptbf[i]; cmax++; } // } //} //f_avgmin[1] /= (float)cmin; f_avgmax[1] /= (float)cmax; //cmin = 0; cmax = 0; //for (int i = 0; i < width * height; i++) //{ // if (!isnan<float>(f_pptbf[i])) // { // if (f_pptbf[i] < f_avg) // { // if (f_pptbf[i] < f_avgmin[1]) { f_avgmin[0] += f_pptbf[i]; cmin++; } // else { f_avgmin[2] += f_pptbf[i]; cmax++; } // } // } //} //f_avgmin[0] /= (float)cmin; f_avgmin[2] /= (float)cmax; //cmin = 0; cmax = 0; //for (int i = 0; i < width * height; i++) //{ // if (!isnan<float>(f_pptbf[i])) // { // if (f_pptbf[i] > f_avg) // { // if (f_pptbf[i] < f_avgmax[1]) { f_avgmax[0] += f_pptbf[i]; cmin++; } // else { f_avgmax[2] += f_pptbf[i]; cmax++; } // } // } //} //f_avgmax[0] /= (float)cmin; f_avgmax[2] /= (float)cmax; const int bins = 100; float histo[bins]; for (int i = 0; i < bins; i++) histo[i] = 0.0f; for (int i = 0; i < width * height; i++) { if (f_pptbf[i] < f_avg) f_pptbf[i] = (f_pptbf[i] - f_min) / (f_avg - f_min)*0.5; else f_pptbf[i] = (f_pptbf[i] - f_avg) / (f_max - f_avg)*0.5+0.5; int iv = (int)((float)(bins)*f_pptbf[i]); if (iv >= bins) iv = bins - 1; histo[iv] += 1.0f / (float)(width * height); //if (f_pptbf[i] < f_avgmin[0]) f_pptbf[i] = (f_pptbf[i] - f_min) / (f_avgmin[0] - f_min)*0.125; //else if (f_pptbf[i] < f_avgmin[1]) f_pptbf[i] = (f_pptbf[i] - f_avgmin[0]) / (f_avgmin[1] - f_avgmin[0])*0.125+0.125; //else if (f_pptbf[i] < f_avgmin[2]) f_pptbf[i] = (f_pptbf[i] - f_avgmin[1]) / (f_avgmin[2] - f_avgmin[1])*0.125 + 0.25; //else if (f_pptbf[i] < f_avg) f_pptbf[i] = (f_pptbf[i] - f_avgmin[2]) / (f_avg - f_avgmin[2])*0.125+0.375; //else if (f_pptbf[i] < f_avgmax[0]) f_pptbf[i] = (f_pptbf[i] - f_avg) / (f_avgmax[0] - f_avg)*0.125 + 0.5; //else if (f_pptbf[i] < f_avgmax[1]) f_pptbf[i] = (f_pptbf[i] - f_avgmax[0]) / (f_avgmax[1] - f_avgmax[0])*0.125 + 0.625; //else if (f_pptbf[i] < f_avgmax[2]) f_pptbf[i] = (f_pptbf[i] - f_avgmax[1]) / (f_avgmax[2] - f_avgmax[1])*0.125 + 0.75; //else f_pptbf[i] = (f_pptbf[i] - f_avgmax[2]) / (f_max - f_avgmax[2])*0.125 + 0.875; } int i; float sum = 0.0; for (i = 0; i < bins && sum < percent; i++) sum += histo[i]; //if (i == bins) return vmax; float ratio = (percent - (sum - histo[i])) / histo[i]; //float ratio = 0.5f; //float ratio = 0.5f; //printf("compute Thresh bin =%d, sum=%g, percent=%g\n", i, sum, percent); float rangea = ((float)(i - 1) / (float)bins + ratio / (float)bins); keep[k] = true; #if 0 for (int i = 0; i < width * height; i++) { if (f_pptbf[i] > rangea) f_pptbf[i] = 1.0; else f_pptbf[i] = 0.0; } #endif if (keep[k]) { // Deformation turbAmplitude0 = turbulenceAmplitude0Array[k]; turbAmplitude1 = turbulenceAmplitude1Array[k]; turbAmplitude2 = turbulenceAmplitude2Array[k]; // Model Transform resolution = modelResolutionArray[k]; rotation = modelAlphaArray[k] / M_PI; rescalex = modelRescalexArray[k]; // Point process do_tiling = tilingTypeArray[k]; jittering = jitteringArray[k]; // Window function windowShape = windowShapeArray[k]; windowArity = windowArityArray[k]; windowLarp = windowLarpArray[k]; windowNorm = windowNormArray[k]; windowSmoothness = windowSmoothArray[k]; windowBlend = windowBlendArray[k]; windowSigwcell = windowSigwcellArray[k]; // Feature function featureBombing = featureBombingArray[k]; featureNorm = featureNormArray[k]; featureWinfeatcorrel = featureWinfeatcorrelArray[k]; featureAniso = featureAnisoArray[k]; featureMinNbKernels = featureMinNbKernelsArray[k]; featureMaxNbKernels = featureMaxNbKernelsArray[k]; featureSigcos = featureSigcosArray[k]; featureSigcosvar = featureSigcosvarArray[k]; featureFrequency = featureFrequencyArray[k]; featurePhaseShift = featurePhaseShiftArray[k]/M_PI/0.5; featureThickness = featureThicknessArray[k]; featureCurvature = featureCurvatureArray[k]; featureOrientation = featureOrientationArray[k]/M_PI; fprintf(fdn, "%02d %02d %d %d %d\n", 0, do_tiling, 0, 0, 0); fprintf(fdn, "%06d %g %d %d\n", pptbf_keep_count, 0.0, 0, 0); fprintf(fdn, "%06d %g %d %g %g %g %g %g %d %g %g %g %g %g %g %d %g %g %g %d %d %g %g %d %g %g %g %g\n", pptbf_keep_count, jittering, resolution, rotation, rescalex, turbAmplitude0, turbAmplitude1, turbAmplitude2, windowShape, windowArity, windowLarp, windowNorm, windowSmoothness, windowBlend, windowSigwcell, featureBombing, featureNorm, featureWinfeatcorrel, featureAniso, featureMinNbKernels, featureMaxNbKernels, featureSigcos, featureSigcosvar, featureFrequency, featurePhaseShift, featureThickness, featureCurvature, featureOrientation); pptbf_keep_count++; fflush(fd); } // else printf("erased %d as it looks like %d\n", k, r-1); if (keep[k]) { std::vector< float > f_pptbf_binary(width * height); f_pptbf_binary = f_pptbf; for (int i = 0; i < width * height; i++) { if (f_pptbf_binary[i] > rangea) f_pptbf_binary[i] = 1.0; else f_pptbf_binary[i] = 0.0; } // Convert data (float to unsigned char) // TODO: maybe use for_each with a lambda doing the "cast" directly instead? std::transform(f_pptbf.begin(), f_pptbf.end(), f_pptbf.begin(), std::bind(std::multiplies< float >(), std::placeholders::_1, 255.f)); std::vector< unsigned char > u_pptbf(f_pptbf.begin(), f_pptbf.end()); // Save data in image //const std::string pptbfName = std::string( "pptbf_" )/*name*/ + std::to_string( i ); char numbuff[100]; sprintf(numbuff, "_%d_%06d", descriptor,pptbf_keep_count - 1); const std::string pptbfName = std::string("pptbf")/*name*/ + std::string(numbuff); //+ std::string( "_D_" ) + std::to_string( d_0 ) + std::string( "_" ) + std::to_string( d_1 ) + std::string( "_" ) + std::to_string( d_2 ) //+ std::string( "_M_" ) + std::to_string( m_0 ) + std::string( "_" ) + std::to_string( m_1 ) + std::string( "_" ) + std::to_string( m_2 ) //+ std::string( "_P_" ) + std::to_string( p_0 ) + std::string( "_" ) + std::to_string( p_1 ) //+ std::string( "_W_" ) + std::to_string( w_0 ) + std::string( "_" ) + std::to_string( w_1 ) + std::string( "_" ) + std::to_string( w_2 ) // + std::string( "_" ) + std::to_string( w_3 ) + std::string( "_" ) + std::to_string( w_4 ) + std::string( "_" ) + std::to_string( w_5 ) // + std::string( "_" ) + std::to_string( w_6 ) //+ std::string( "_F_" ) + std::to_string( f_0 ) + std::string( "_" ) + std::to_string( f_1 ) + std::string( "_" ) + std::to_string( f_2 ) // + std::string( "_" ) + std::to_string( f_3 ) + std::string( "_" ) + std::to_string( f_4 ) + std::string( "_" ) + std::to_string( f_5 ) // + std::string( "_" ) + std::to_string( f_6 ) + std::string( "_" ) + std::to_string( f_7 ) + std::string( "_" ) + std::to_string( f_8 ) // + std::string( "_" ) + std::to_string( f_9 ) + std::string( "_" ) + std::to_string( f_10 ) + std::string( "_" ) + std::to_string( f_11 ) // + std::string( "_" ) + std::to_string( f_12 ); const std::string pptbfFilename = databasePath + pptbfName + std::string(".png"); PtImageHelper::saveImage(pptbfFilename.c_str(), width, height, 1/*nb channels*/, u_pptbf.data()); // Binary version { // Convert data (float to unsigned char) // TODO: maybe use for_each with a lambda doing the "cast" directly instead? std::transform(f_pptbf_binary.begin(), f_pptbf_binary.end(), f_pptbf_binary.begin(), std::bind(std::multiplies< float >(), std::placeholders::_1, 255.f)); std::vector< unsigned char > u_pptbf(f_pptbf_binary.begin(), f_pptbf_binary.end()); // Save data in image //const std::string pptbfName = std::string( "pptbf_" )/*name*/ + std::to_string( i ); char numbuff[100]; sprintf(numbuff, "_%d_%06d", descriptor, pptbf_keep_count - 1); const std::string pptbfName = std::string("pptbf")/*name*/ + std::string(numbuff); //+ std::string( "_D_" ) + std::to_string( d_0 ) + std::string( "_" ) + std::to_string( d_1 ) + std::string( "_" ) + std::to_string( d_2 ) //+ std::string( "_M_" ) + std::to_string( m_0 ) + std::string( "_" ) + std::to_string( m_1 ) + std::string( "_" ) + std::to_string( m_2 ) //+ std::string( "_P_" ) + std::to_string( p_0 ) + std::string( "_" ) + std::to_string( p_1 ) //+ std::string( "_W_" ) + std::to_string( w_0 ) + std::string( "_" ) + std::to_string( w_1 ) + std::string( "_" ) + std::to_string( w_2 ) // + std::string( "_" ) + std::to_string( w_3 ) + std::string( "_" ) + std::to_string( w_4 ) + std::string( "_" ) + std::to_string( w_5 ) // + std::string( "_" ) + std::to_string( w_6 ) //+ std::string( "_F_" ) + std::to_string( f_0 ) + std::string( "_" ) + std::to_string( f_1 ) + std::string( "_" ) + std::to_string( f_2 ) // + std::string( "_" ) + std::to_string( f_3 ) + std::string( "_" ) + std::to_string( f_4 ) + std::string( "_" ) + std::to_string( f_5 ) // + std::string( "_" ) + std::to_string( f_6 ) + std::string( "_" ) + std::to_string( f_7 ) + std::string( "_" ) + std::to_string( f_8 ) // + std::string( "_" ) + std::to_string( f_9 ) + std::string( "_" ) + std::to_string( f_10 ) + std::string( "_" ) + std::to_string( f_11 ) // + std::string( "_" ) + std::to_string( f_12 ); const std::string pptbfFilename = databasePath + pptbfName + std::string("_binary.png"); PtImageHelper::saveImage(pptbfFilename.c_str(), width, height, 1/*nb channels*/, u_pptbf.data()); } } // Update counter //i++; } fclose(fdn); // Reset GL state(s) // - Unset shader program PtShaderProgram::unuse(); // LOG info std::cout << "Finished..." << pptbf_count << std::endl; } /****************************************************************************** * Generate a PPTBF given a parameter file ******************************************************************************/ void PtGraphicsPPTBF::generatePPTBF( const unsigned int pWidth, const unsigned int pHeight, const char* pParameterFilename ) { assert( pWidth != 0 && pHeight != 0 ); //-------------------------------------------------------------------------- /** * PPTBF data type enumeration */ enum class PPTBFDataType { // Point process eTilingType = 0, eJittering, // Transformation eResolution, eRotation, eAspectRatio, // Turbulence eDistorsionBaseAmplitude, eDistorsionAmplitudeGain, eDistorsionFrequency, // Window function eWindowShape, eWindowArity, eWindowLarp, eWindowNorm, eWindowSmoothness, eWindowBlend, eWindowSigwcell, // Feature function eFeatureBombing, eFeatureNorm, eFeatureWinfeatcorrel, eFeatureAniso, eFeatureMinNbKernels, eFeatureMaxNbKernels, eFeatureSigcos, eFeatureSigcosvar, eFeatureFrequency, eFeaturePhaseShift, eFeatureThickness, eFeatureCurvature, eFeatureOrientation, // counter ePPTBFDataTypes }; // LOG info std::cout << "\nPPTBF generation..." << std::endl; std::cout << "START..." << std::endl; const int width = pWidth; const int height = pHeight; // Resize graphics resources onSizeModified( width, height ); /////////////////////////////////////////// // Read USER parameters /////////////////////////////////////////// //----------------------------------------- //// extract image name //const std::string filename = std::string( pParameterFilename ); //size_t lastindex = filename.find_last_of( "/\\" ); //std::string textureDirectory = filename.substr( 0, lastindex ); //std::string textureName = filename.substr( 0, lastindex ); //----------------------------------------- //----------------------------------------- // Extract image name // - filename const std::string filename = std::string( pParameterFilename ); // - image directory const size_t directoryIndex = filename.find_last_of( "/\\" ); const std::string textureDirectory = filename.substr( 0, directoryIndex ); // - file extension const size_t extensionIndex = filename.find_last_of( "." ); const std::string imageExtension = filename.substr( extensionIndex + 1 ); // - image name std::string imageName = filename.substr( directoryIndex + 1 ); const size_t nameIndex = imageName.find_last_of( "." ); const std::string pptbfParameterSuffix = "_pptbf_params"; imageName = imageName.substr( 0, nameIndex - pptbfParameterSuffix.size() ); std::string textureName = imageName; //----------------------------------------- std::ifstream estimatedParameterFile( pParameterFilename ); std::string lineData; // Get threshold float threshold; std::getline( estimatedParameterFile, lineData ); std::stringstream ssthreshold( lineData ); ssthreshold >> threshold; // Get PPTBF parameters std::getline( estimatedParameterFile, lineData ); // LOG info std::cout << std::endl; std::cout << "--------------------------------------------------------" << std::endl; std::cout << "PPTBF" << std::endl; std::cout << "--------------------------------------------------------" << std::endl; std::cout << std::endl; // PPTBF parameters std::vector< float > pptbf; std::stringstream sspptbf( lineData ); float value; while ( sspptbf >> value ) { // Fill parameters pptbf.push_back( value ); } // Point Process const int pointProcess_tilingType = static_cast< int >( pptbf[ static_cast< int >( PPTBFDataType::eTilingType ) ] ); const float pointProcess_jittering = pptbf[ static_cast< int >( PPTBFDataType::eJittering ) ]; std::cout << "[POINT PROCESS]" << std::endl; std::cout << "tiling type: " << pointProcess_tilingType << std::endl; std::cout << "jittering: " << pointProcess_jittering << std::endl; // Transformation std::cout << std::endl; const int transformation_resolution = static_cast< int >( pptbf[ static_cast< int >( PPTBFDataType::eResolution ) ] ); const float transformation_rotation = pptbf[ static_cast< int >( PPTBFDataType::eRotation ) ] * M_PI; const float transformation_aspectRatio = pptbf[ static_cast< int >( PPTBFDataType::eAspectRatio ) ]; std::cout << "[TRANSFORMATION]" << std::endl; std::cout << "resolution: " << transformation_resolution << std::endl; std::cout << "rotation: " << transformation_rotation << std::endl; std::cout << "aspectRatio: " << transformation_aspectRatio << std::endl; // Turbulence std::cout << std::endl; const float distorsion_baseAmplitude = pptbf[ static_cast< int >( PPTBFDataType::eDistorsionBaseAmplitude ) ]; const float distorsion_amplitudeGain = pptbf[ static_cast< int >( PPTBFDataType::eDistorsionAmplitudeGain ) ]; const float distorsion_frequency = pptbf[ static_cast< int >( PPTBFDataType::eDistorsionFrequency ) ]; std::cout << "[TURBULENCE]" << std::endl; std::cout << "base amplitude: " << distorsion_baseAmplitude << std::endl; std::cout << "gain: " << distorsion_amplitudeGain << std::endl; std::cout << "frequency: " << distorsion_frequency << std::endl; // Window Function std::cout << std::endl; std::cout << "[WINDOW FUNCTION]" << std::endl; const int window_shape = static_cast< int >( pptbf[ static_cast< int >( PPTBFDataType::eWindowShape ) ] ); const float window_arity = pptbf[ static_cast< int >( PPTBFDataType::eWindowArity ) ]; const float window_larp = pptbf[ static_cast< int >( PPTBFDataType::eWindowLarp ) ]; const float window_norm = pptbf[ static_cast< int >( PPTBFDataType::eWindowNorm ) ]; const float window_smoothness = pptbf[ static_cast< int >( PPTBFDataType::eWindowSmoothness ) ]; const float window_blend = pptbf[ static_cast< int >( PPTBFDataType::eWindowBlend ) ]; const float window_decay = pptbf[ static_cast< int >( PPTBFDataType::eWindowSigwcell ) ]; std::cout << "shape: " << window_shape << std::endl; std::cout << "arity: " << window_arity << std::endl; std::cout << "larp: " << window_larp << std::endl; std::cout << "norm: " << window_norm << std::endl; std::cout << "smoothness: " << window_smoothness << std::endl; std::cout << "blend: " << window_blend << std::endl; std::cout << "decay: " << window_decay << std::endl; // Feature Function std::cout << std::endl; const int feature_type = static_cast< int >( pptbf[ static_cast< int >( PPTBFDataType::eFeatureBombing ) ] ); const float feature_norm = pptbf[ static_cast< int >( PPTBFDataType::eFeatureNorm ) ]; const float feature_featureCorrelation = pptbf[ static_cast< int >( PPTBFDataType::eFeatureWinfeatcorrel ) ]; const float feature_anisotropy = pptbf[ static_cast< int >( PPTBFDataType::eFeatureAniso ) ]; const int feature_nbMinKernels = static_cast< int >( pptbf[ static_cast< int >( PPTBFDataType::eFeatureMinNbKernels ) ] ); const int feature_nbMaxKernels = static_cast< int >( pptbf[ static_cast< int >( PPTBFDataType::eFeatureMaxNbKernels ) ] ); const float feature_decay = pptbf[ static_cast< int >( PPTBFDataType::eFeatureSigcos ) ]; const float feature_decayDelta = pptbf[ static_cast< int >( PPTBFDataType::eFeatureSigcosvar ) ]; const int feature_frequency = static_cast< int >( pptbf[ static_cast< int >( PPTBFDataType::eFeatureFrequency ) ] ); const float feature_phaseShift = pptbf[ static_cast< int >( PPTBFDataType::eFeaturePhaseShift ) ] * M_PI * 0.5; const float feature_thickness = pptbf[ static_cast< int >( PPTBFDataType::eFeatureThickness ) ]; const float feature_curvature = pptbf[ static_cast< int >( PPTBFDataType::eFeatureCurvature ) ]; const float feature_orientation = pptbf[ static_cast< int >( PPTBFDataType::eFeatureOrientation ) ] * M_PI; std::cout << "[FEATURE FUNCTION]" << std::endl; std::cout << "type: " << feature_type << std::endl; std::cout << "norm: " << feature_norm << std::endl; std::cout << "window feature correlation: " << feature_featureCorrelation << std::endl; std::cout << "anisotropy: " << feature_anisotropy << std::endl; std::cout << "nb min kernels: " << feature_nbMinKernels << std::endl; std::cout << "nb max kernels: " << feature_nbMaxKernels << std::endl; std::cout << "decay: " << feature_decay << std::endl; std::cout << "decay delta: " << feature_decayDelta << std::endl; std::cout << "frequency: " << feature_frequency << std::endl; std::cout << "phase shift: " << feature_phaseShift << std::endl; std::cout << "thickness: " << feature_thickness << std::endl; std::cout << "curvature: " << feature_curvature << std::endl; std::cout << "orientation: " << feature_orientation << std::endl; /////////////////////// // Set common GL states /////////////////////// //setImageWidth( width ); //setImageHeight( height ); setWidth( width ); setHeight( height ); // Set shader program PtShaderProgram* shaderProgram = mMegakernelShaderProgram; shaderProgram->use(); // Set texture(s) // - PRNG glBindTextureUnit( 0/*unit*/, mTexture_P ); // - noise glBindTextureUnit( 1/*unit*/, mTexture_rnd_tab ); // Set sampler(s) // - PRNG glBindSampler( 0/*unit*/, mSampler_PRNG_Noise ); // - noise glBindSampler( 1/*unit*/, mSampler_PRNG_Noise ); // Set image(s) // - PPTBF (output) glBindImageTexture( 0/*unit*/, mPPTBFTexture, 0/*level*/, GL_FALSE/*layered*/, 0/*layer*/, GL_WRITE_ONLY, GL_R32F ); // Set uniform(s) // - PRNG shaderProgram->set( 0, "uPermutationTex" ); // - noise shaderProgram->set( 1, "uNoiseTex" ); // Kernel configuration // - block const int blockSizeX = 8; // TODO: benchmark with 8x8, 16x16 and 32x32 const int blockSizeY = 8; // - grid const GLuint gridSizeX = glm::max( ( width + blockSizeX - 1 ) / blockSizeX, 1 ); const GLuint gridSizeY = glm::max( ( height + blockSizeY - 1 ) / blockSizeY, 1 ); ///////////////////////////////////////// // Sampling the space of PPTBF structures ///////////////////////////////////////// //////////////// // Point Process //////////////// shaderProgram->set( pointProcess_tilingType, "uPointProcessTilingType" ); shaderProgram->set( pointProcess_jittering, "uPointProcessJitter" ); ////////////////// // Model Transform ////////////////// shaderProgram->set( transformation_resolution, "uResolution" ); shaderProgram->set( transformation_rotation, "uRotation" ); shaderProgram->set( transformation_aspectRatio, "uRescaleX" ); ////////////// // Deformation ////////////// shaderProgram->set( distorsion_baseAmplitude, "uTurbulenceAmplitude_0" ); shaderProgram->set( distorsion_amplitudeGain, "uTurbulenceAmplitude_1" ); shaderProgram->set( distorsion_frequency, "uTurbulenceAmplitude_2" ); ////////////////// // Window Function ////////////////// shaderProgram->set( window_shape, "uWindowShape" ); shaderProgram->set( window_arity, "uWindowArity" ); shaderProgram->set( window_larp, "uWindowLarp" ); shaderProgram->set( window_norm, "uWindowNorm" ); shaderProgram->set( window_smoothness, "uWindowSmooth" ); shaderProgram->set( window_blend, "uWindowBlend" ); shaderProgram->set( window_decay, "uWindowSigwcell" ); /////////////////// // Feature Function /////////////////// shaderProgram->set( feature_type, "uFeatureBomb" ); shaderProgram->set( feature_norm, "uFeatureNorm" ); shaderProgram->set( feature_featureCorrelation, "uFeatureWinfeatcorrel" ); shaderProgram->set( feature_anisotropy, "uFeatureAniso" ); shaderProgram->set( feature_nbMinKernels, "uFeatureNpmin" ); shaderProgram->set( feature_nbMaxKernels, "uFeatureNpmax" ); shaderProgram->set( feature_decay, "uFeatureSigcos" ); shaderProgram->set( feature_decayDelta, "uFeatureSigcosvar" ); shaderProgram->set( feature_frequency, "uFeatureFreq" ); shaderProgram->set( feature_phaseShift, "uFeaturePhase" ); shaderProgram->set( feature_thickness, "uFeatureThickness" ); shaderProgram->set( feature_curvature, "uFeatureCourbure" ); shaderProgram->set( feature_orientation, "uFeatureDeltaorient" ); //---------------------------------------------------------------------------------------------- // - labeling shaderProgram->set( /*getNbLabels()*/0, "uNbLabels" ); // TODO: check this !!!! //// - default translation //shaderProgram->set( /*getShiftX()*/0.f, "uShiftX" ); // TODO: check this !!!! //shaderProgram->set( /*getShiftY()*/0.f, "uShiftY" ); // TODO: check this !!!! // - "parameter estimation" tool shaderProgram->set( /*getShiftX()*/10.f, "uShiftX" ); // TODO: check this !!!! shaderProgram->set( /*getShiftY()*/10.f, "uShiftY" ); // TODO: check this !!!! // - labeling glBindImageTexture( 1/*unit*/, mPPTBFLabelMap, 0/*level*/, GL_FALSE/*layered*/, 0/*layer*/, GL_WRITE_ONLY, GL_R8UI ); // - labeling glBindImageTexture( 2/*unit*/, mPPTBFRandomValueMap, 0/*level*/, GL_FALSE/*layered*/, 0/*layer*/, GL_WRITE_ONLY, GL_R32F ); //---------------------------------------------------------------------------------------------- //--------------------- // Generate PPTBF image //--------------------- std::cout << "generating image..." << std::endl; // Launch mega-kernel glDispatchCompute( gridSizeX, gridSizeY, 1 ); // Synchronization // - make sure writing to image has finished before read glMemoryBarrier( GL_SHADER_IMAGE_ACCESS_BARRIER_BIT ); // pb: wait for nothing? use a boolean if someone need to sample texture glMemoryBarrier( GL_ALL_BARRIER_BITS ); //------------------- // Export PPTBF image //------------------- // Retrieve data on host std::vector< float > f_pptbf( width * height ); #if 1 // - deal with odd texture dimensions glPixelStorei( GL_PACK_ALIGNMENT, 1 ); #endif glGetTextureImage( mPPTBFTexture, 0/*level*/, GL_RED, GL_FLOAT, sizeof( float ) * width * height, f_pptbf.data() ); std::vector<float>::iterator it = f_pptbf.begin(); float max_value = f_pptbf[0]; float min_value = f_pptbf[0]; while (it != f_pptbf.end()) { if ((*it) > max_value) max_value = (*it); if ((*it) < min_value) min_value = (*it); ++it; } std::cout << "Max value: " << max_value << std::endl; std::cout << "Min value: " << min_value << std::endl; for (int i = 0; i < width * height; i++) f_pptbf[i] = f_pptbf[i] / max_value; //----------------------------------------------------------------------------------------------------------------------------------- /* unsigned int cc = 0; // TESTing for "nan" and "inf" for (int i = 0; i < width * height; i++) { #ifdef _WIN32 if (isnan<float>(f_pptbf[i]) || isinf<float>(f_pptbf[i])) // TODO: add isinf also? #else if (isnan(f_pptbf[i]) || isinf(f_pptbf[i])) // TODO: add isinf also? #endif { if (isinf<float>(f_pptbf[i])) cc++; f_pptbf[i] = 0.f; } } std::cout << "Is inf: " << cc << std::endl; */ //------------------- // Export data //------------------- { // Convert data (float to unsigned char) // TODO: maybe use for_each with a lambda doing the "cast" directly instead? std::transform( f_pptbf.begin(), f_pptbf.end(), f_pptbf.begin(), std::bind( std::multiplies< float >(), std::placeholders::_1, 255.f ) ); std::vector< unsigned char > u_pptbf(f_pptbf.begin(), f_pptbf.end()); // Save data in image //const std::string pptbfName = std::string( "pptbf_" )/*name*/ + std::to_string( i ); char numbuff[100]; //const std::string pptbfName = std::string( "pptbf_TEST" )/*name*/; const std::string pptbfName = textureName + std::string( "_pptbf" ); const std::string pptbfFilename = textureDirectory + std::string( "/" ) + pptbfName + std::string( ".png" ); //const std::string pptbfFilename = pptbfName + std::string(".png"); std::cout << "write PPTBF: " << pptbfFilename << std::endl; PtImageHelper::saveImage( pptbfFilename.c_str(), width, height, 1/*nb channels*/, u_pptbf.data() ); } //----------------------------------------------------------------------------------------------------------------------------------- //------------------- // make approximate histogramm equalization //------------------- //std::cout << "----------- 0" << std::endl; //------------------- // TEST //const float percent = threshold; const float percent = 1.f - threshold; //------------------- float f_avg = 0.0; float f_min = 0.0, f_max = 0.0; int count = 0; for (int i = 0; i < width * height; i++) { #ifdef _WIN32 if ( !isnan<float>(f_pptbf[i]) && !isinf<float>(f_pptbf[i]) ) // TODO: add isinf also? #else if ( !isnan(f_pptbf[i]) && !isinf(f_pptbf[i]) ) // TODO: add isinf also? #endif { f_avg += f_pptbf[i]; count++; if (i == 0) { f_min = f_avg; f_max = f_avg; } if (f_min > f_pptbf[i]) f_min = f_pptbf[i]; if (f_max < f_pptbf[i]) f_max = f_pptbf[i]; } } if ( count > 0 ) { f_avg /= (float)(count); } //std::cout << "avg=" << f_avg << ", min=" << f_min << ", max=" << f_max << "\n"; //int cmin = 0, cmax = 0; //float f_avgmin[3] = { 0.0, 0.0, 0.0 }, f_avgmax[3] = { 0.0,0.0,0.0 }; //for (int i = 0; i < width * height; i++) //{ // if (!isnan<float>(f_pptbf[i])) // { // if (f_pptbf[i] < f_avg) { f_avgmin[1] += f_pptbf[i]; cmin++; } // else { f_avgmax[1] += f_pptbf[i]; cmax++; } // } //} //f_avgmin[1] /= (float)cmin; f_avgmax[1] /= (float)cmax; //cmin = 0; cmax = 0; //for (int i = 0; i < width * height; i++) //{ // if (!isnan<float>(f_pptbf[i])) // { // if (f_pptbf[i] < f_avg) // { // if (f_pptbf[i] < f_avgmin[1]) { f_avgmin[0] += f_pptbf[i]; cmin++; } // else { f_avgmin[2] += f_pptbf[i]; cmax++; } // } // } //} //f_avgmin[0] /= (float)cmin; f_avgmin[2] /= (float)cmax; //cmin = 0; cmax = 0; //for (int i = 0; i < width * height; i++) //{ // if (!isnan<float>(f_pptbf[i])) // { // if (f_pptbf[i] > f_avg) // { // if (f_pptbf[i] < f_avgmax[1]) { f_avgmax[0] += f_pptbf[i]; cmin++; } // else { f_avgmax[2] += f_pptbf[i]; cmax++; } // } // } //} //f_avgmax[0] /= (float)cmin; f_avgmax[2] /= (float)cmax; //std::cout << "----------- 1" << std::endl; const int bins = 100; float histo[bins]; for (int i = 0; i < bins; i++) histo[i] = 0.0f; for (int i = 0; i < width * height; i++) { #ifdef _WIN32 if ( !isnan<float>(f_pptbf[i]) && !isinf<float>(f_pptbf[i]) ) // TODO: add isinf also? #else if ( !isnan(f_pptbf[i]) && !isinf(f_pptbf[i]) ) // TODO: add isinf also? #endif { if (f_pptbf[i] < f_avg) { f_pptbf[i] = (f_pptbf[i] - f_min) / (f_avg - f_min)*0.5; } else { f_pptbf[i] = (f_pptbf[i] - f_avg) / (f_max - f_avg)*0.5 + 0.5; } int iv = (int)((float)(bins)*f_pptbf[i]); if (iv >= bins) iv = bins - 1; histo[iv] += 1.0f / (float)(width * height); } //if (f_pptbf[i] < f_avgmin[0]) f_pptbf[i] = (f_pptbf[i] - f_min) / (f_avgmin[0] - f_min)*0.125; //else if (f_pptbf[i] < f_avgmin[1]) f_pptbf[i] = (f_pptbf[i] - f_avgmin[0]) / (f_avgmin[1] - f_avgmin[0])*0.125+0.125; //else if (f_pptbf[i] < f_avgmin[2]) f_pptbf[i] = (f_pptbf[i] - f_avgmin[1]) / (f_avgmin[2] - f_avgmin[1])*0.125 + 0.25; //else if (f_pptbf[i] < f_avg) f_pptbf[i] = (f_pptbf[i] - f_avgmin[2]) / (f_avg - f_avgmin[2])*0.125+0.375; //else if (f_pptbf[i] < f_avgmax[0]) f_pptbf[i] = (f_pptbf[i] - f_avg) / (f_avgmax[0] - f_avg)*0.125 + 0.5; //else if (f_pptbf[i] < f_avgmax[1]) f_pptbf[i] = (f_pptbf[i] - f_avgmax[0]) / (f_avgmax[1] - f_avgmax[0])*0.125 + 0.625; //else if (f_pptbf[i] < f_avgmax[2]) f_pptbf[i] = (f_pptbf[i] - f_avgmax[1]) / (f_avgmax[2] - f_avgmax[1])*0.125 + 0.75; //else f_pptbf[i] = (f_pptbf[i] - f_avgmax[2]) / (f_max - f_avgmax[2])*0.125 + 0.875; } //std::cout << "----------- 2" << std::endl; int i; float sum = 0.0; for (i = 0; i < bins && sum < percent; i++) sum += histo[i]; //if (i == bins) return vmax; float ratio = 0.f; if ( histo[i] > 0.f ) { ratio = ( percent - (sum - histo[i]) ) / histo[i]; } //float ratio = 0.5f; //printf("compute Thresh bin =%d, sum=%g, percent=%g\n", i, sum, percent); float rangea = ((float)(i - 1) / (float)bins + ratio / (float)bins); for (int i = 0; i < width * height; i++) { //if (isnan<float>(f_pptbf[i]) ) // TODO: add isinf also? //{ // int test = 0; // test++; //} //if (isinf<float>(f_pptbf[i])) // TODO: add isinf also? //{ // int test = 0; // test++; //} if (f_pptbf[i] > rangea) f_pptbf[i] = 1.0; else f_pptbf[i] = 0.0; } //----------------------------------------------------------------------------------------------------------------------------------- //std::cout << "----------- 3" << std::endl; //------------------- // Export data //------------------- // Convert data (float to unsigned char) // TODO: maybe use for_each with a lambda doing the "cast" directly instead? std::transform( f_pptbf.begin(), f_pptbf.end(), f_pptbf.begin(), std::bind( std::multiplies< float >(), std::placeholders::_1, 255.f ) ); std::vector< unsigned char > u_pptbf(f_pptbf.begin(), f_pptbf.end()); // Save data in image //const std::string pptbfName = std::string( "pptbf_" )/*name*/ + std::to_string( i ); char numbuff[100]; //const std::string pptbfName = std::string( "pptbf_binary_TEST" )/*name*/; const std::string pptbfName = textureName + std::string( "_pptbf_binary" ); const std::string pptbfFilename = textureDirectory + std::string( "/" ) + pptbfName + std::string( ".png" ); //const std::string pptbfFilename = pptbfName + std::string( ".png" ); std::cout << "write PPTBF binary: " << pptbfFilename << std::endl; PtImageHelper::saveImage( pptbfFilename.c_str(), width, height, 1/*nb channels*/, u_pptbf.data() ); //std::cout << "----------- 4" << std::endl; // Reset GL state(s) // - Unset shader program PtShaderProgram::unuse(); // LOG info std::cout << "Finished..." << std::endl; }
205,287
C++
.cpp
4,637
40.210697
413
0.636358
ASTex-ICube/semiproctex
39
8
2
LGPL-2.1
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,919
PtShaderProgram.cpp
ASTex-ICube_semiproctex/PPTBF_Structures_Src/PtGraphics/PtShaderProgram.cpp
/* * Publication: Semi-Procedural Textures Using Point Process Texture Basis Functions * Authors: anonymous * * Code author: Pascal Guehl * * anonymous * anonymous */ /** * @version 1.0 */ #include "PtShaderProgram.h" /****************************************************************************** ******************************* INCLUDE SECTION ****************************** ******************************************************************************/ // STL #include <string> #include <iostream> #include <vector> #include <fstream> #include <sstream> #include <fstream> #include <cerrno> #include <cassert> /****************************************************************************** ****************************** NAMESPACE SECTION ***************************** ******************************************************************************/ // GigaVoxels using namespace PtGraphics; /****************************************************************************** ************************* DEFINE AND CONSTANT SECTION ************************ ******************************************************************************/ const char* PtShaderProgram::ShaderTypeName[ static_cast< int >( PtShaderProgram::ShaderType::eNbShaderTypes ) ] = { "Vertex", "Tesselation Control", "TesselationEvaluation", "Geometry", "Fragment", "Compute" }; /****************************************************************************** ***************************** TYPE DEFINITION ******************************** ******************************************************************************/ /****************************************************************************** ***************************** METHOD DEFINITION ****************************** ******************************************************************************/ /****************************************************************************** * Constructor ******************************************************************************/ PtShaderProgram::PtShaderProgram() : _vertexShaderFilename() , _tesselationControlShaderFilename() , _tesselationEvaluationShaderFilename() , _geometryShaderFilename() , _fragmentShaderFilename() , _computeShaderFilename() , _vertexShaderSourceCode() , _tesselationControlShaderSourceCode() , _tesselationEvaluationShaderSourceCode() , _geometryShaderSourceCode() , _fragmentShaderSourceCode() , _computeShaderSourceCode() , _program( 0 ) , _vertexShader( 0 ) , _tesselationControlShader( 0 ) , _tesselationEvaluationShader( 0 ) , _geometryShader( 0 ) , _fragmentShader( 0 ) , _computeShader( 0 ) , _linked( false ) , mName() , mInfo() { // Initialize graphics resources //initialize(); // NO: to avoid crash if graphics context has not been initialized !!!! } /****************************************************************************** * Desconstructor ******************************************************************************/ PtShaderProgram::~PtShaderProgram() { // Release graphics resources finalize(); } /****************************************************************************** * Initialize ******************************************************************************/ bool PtShaderProgram::initialize() { // First, check if a program has already been created // ... assert( _program == 0 ); // Create program object _program = glCreateProgram(); if ( _program == 0 ) { // LOG // ... return false; } return true; } /****************************************************************************** * Finalize ******************************************************************************/ bool PtShaderProgram::finalize() { // Check all data to release if ( _vertexShader ) { glDetachShader( _program, _vertexShader ); glDeleteShader( _vertexShader ); } if ( _tesselationControlShader ) { glDetachShader( _program, _tesselationControlShader ); glDeleteShader( _tesselationControlShader ); } if ( _tesselationEvaluationShader ) { glDetachShader( _program, _tesselationEvaluationShader ); glDeleteShader( _tesselationEvaluationShader ); } if ( _geometryShader ) { glDetachShader( _program, _geometryShader ); glDeleteShader( _geometryShader ); } if ( _fragmentShader ) { glDetachShader( _program, _fragmentShader ); glDeleteShader( _fragmentShader ); } if ( _computeShader ) { glDetachShader( _program, _computeShader ); glDeleteShader( _computeShader ); } // Delete program object if ( _program ) { glDeleteProgram( _program ); // Reset value ? _program = 0; } _linked = false; return true; } /****************************************************************************** * Compile shader ******************************************************************************/ bool PtShaderProgram::addShader( PtShaderProgram::ShaderType pShaderType, const std::string& pShaderFileName ) { assert( _program != 0 ); // Retrieve file content std::string shaderSourceCode; bool isReadFileOK = getFileContent( pShaderFileName, shaderSourceCode ); if ( ! isReadFileOK ) { std::cerr<<"Error: can't read file " << pShaderFileName << std::endl; // LOG // ... return false; } // Create shader object GLuint shader = 0; switch ( pShaderType ) { case ShaderType::eVertexShader: shader = glCreateShader( GL_VERTEX_SHADER ); break; case ShaderType::eTesselationControlShader: shader = glCreateShader( GL_TESS_CONTROL_SHADER ); break; case ShaderType::eTesselationEvaluationShader: shader = glCreateShader( GL_TESS_EVALUATION_SHADER ); break; case ShaderType::eGeometryShader: shader = glCreateShader( GL_GEOMETRY_SHADER ); break; case ShaderType::eFragmentShader: shader = glCreateShader( GL_FRAGMENT_SHADER ); break; //TODO //- protect code if not defined case ShaderType::eComputeShader: shader = glCreateShader( GL_COMPUTE_SHADER ); break; default: // LOG // ... return false; } // Check shader creation error if ( shader == 0 ) { std::cerr << "Error creating shader " << pShaderFileName << std::endl; // LOG // ... return false; } switch ( pShaderType ) { case ShaderType::eVertexShader: _vertexShader = shader; _vertexShaderFilename = pShaderFileName; _vertexShaderSourceCode = shaderSourceCode; break; case ShaderType::eTesselationControlShader: _tesselationControlShader = shader; _tesselationControlShaderFilename = pShaderFileName; _tesselationControlShaderSourceCode = shaderSourceCode; break; case ShaderType::eTesselationEvaluationShader: _tesselationEvaluationShader = shader; _tesselationEvaluationShaderFilename = pShaderFileName; _tesselationEvaluationShaderSourceCode = shaderSourceCode; break; case ShaderType::eGeometryShader: _geometryShader = shader; _geometryShaderFilename = pShaderFileName; _geometryShaderSourceCode = shaderSourceCode; break; case ShaderType::eFragmentShader: _fragmentShader = shader; _fragmentShaderFilename = pShaderFileName; _fragmentShaderSourceCode = shaderSourceCode; break; case ShaderType::eComputeShader: _computeShader = shader; _computeShaderFilename = pShaderFileName; _computeShaderSourceCode = shaderSourceCode; break; default: break; } // Replace source code in shader object const char* source = shaderSourceCode.c_str(); glShaderSource( shader, 1, &source, NULL ); /*int length = shaderSourceCode.size(); glShaderSource( shader, 1, &source, &length );*/ // Compile shader object glCompileShader( shader ); // Check compilation status GLint compileStatus; glGetShaderiv( shader, GL_COMPILE_STATUS, &compileStatus ); if ( compileStatus == GL_FALSE ) { // LOG // ... GLint logInfoLength = 0; glGetShaderiv( shader, GL_INFO_LOG_LENGTH, &logInfoLength ); if ( logInfoLength > 0 ) { // Return information log for shader object GLchar* infoLog = new GLchar[ logInfoLength ]; GLsizei length = 0; glGetShaderInfoLog( shader, logInfoLength, &length, infoLog ); // LOG std::cout << "\nPtShaderProgram::addShader() - compilation ERROR" << std::endl; std::cout << "File : " << pShaderFileName << std::endl; std::cout << infoLog << std::endl; delete[] infoLog; } return false; } else { // Attach shader object to program object glAttachShader( _program, shader ); } return true; } /****************************************************************************** * Link program ******************************************************************************/ bool PtShaderProgram::link() { assert( _program != 0 ); if ( _linked ) { return true; } if ( _program == 0 ) { return false; } // Indicate to the implementation the intention of the application to retrieve the program's binary representation with glGetProgramBinary // NOTE: set this before calling glLinkProgram() glProgramParameteri( _program, GL_PROGRAM_BINARY_RETRIEVABLE_HINT, GL_TRUE ); // Link program object glLinkProgram( _program ); // Check linking status GLint linkStatus = 0; glGetProgramiv( _program, GL_LINK_STATUS, &linkStatus ); if ( linkStatus == GL_FALSE ) { // LOG // ... GLint logInfoLength = 0; glGetProgramiv( _program, GL_INFO_LOG_LENGTH, &logInfoLength ); if ( logInfoLength > 0 ) { // Return information log for program object GLchar* infoLog = new GLchar[ logInfoLength ]; GLsizei length = 0; glGetProgramInfoLog( _program, logInfoLength, &length, infoLog ); // LOG std::cout << "\nPtShaderProgram::link() - compilation ERROR" << std::endl; std::cout << infoLog << std::endl; delete[] infoLog; } return false; } // Update internal state _linked = true; //-------------------- #if 0 // Get a binary representation of a program object's compiled and linked executable source GLint formats = 0; glGetIntegerv( GL_NUM_PROGRAM_BINARY_FORMATS, &formats ); GLint* binaryFormats = new GLint[ formats ]; glGetIntegerv( GL_PROGRAM_BINARY_FORMATS, binaryFormats ); GLint len = 0; glGetProgramiv( _program, GL_PROGRAM_BINARY_LENGTH, &len ); //u8* binary = new u8[len]; //GLenum *binaryFormats = 0; //glGetProgramBinary(progId, len, NULL, (GLenum*)binaryFormats, binary); //FILE* fp = fopen(shader.bin, "wb"); //fwrite(binary, len, 1, fp); //fclose(fp); //delete [] binary; //const size_t MAX_SIZE = 1 << 16; //char binary[ MAX_SIZE ]; char* binary = new char[ len ]; GLenum format; GLint length; //glGetProgramBinary( _program, MAX_SIZE, &length, &format, &binary[ 0 ] ); glGetProgramBinary( _program, len, &length, &format, &binary[ 0 ] ); static int counter = 0; std::string shaderName; if ( ! mName.empty() ) { shaderName = mName; } else { shaderName = std::to_string( counter ); } const std::string assemblyFilename = std::string( "ASM_" ) + shaderName + std::string( ".txt" ); std::ofstream binaryfile( assemblyFilename ); binaryfile.write( binary, length ); binaryfile.close(); delete[] binary; ++counter; #endif //-------------------- return true; } /****************************************************************************** * Initialize program with shaders as (shadertype, filename) ******************************************************************************/ bool PtShaderProgram::initializeProgram( const TShaderList& pShaders ) { bool statusOK = false; // LOG std::cout << "\t" << mInfo << std::endl; // Add shaders std::cout << "\t\tCompiling: "; for ( const auto& data : pShaders ) { // LOG: shader type std::cout << std::string( ShaderTypeName[ static_cast< int >( data.first ) ] ) << " "; // Create, compile and attach shader statusOK = addShader( data.first, data.second ); assert( statusOK ); if ( ! statusOK ) { // TODO: clean resource //... return false; } } // Link program std::cout << "\n\t\tLinking..." << std::endl; statusOK = link(); assert( statusOK ); return statusOK; } /****************************************************************************** * ... * * @param pFilename ... * * @return ... ******************************************************************************/ bool PtShaderProgram::getFileContent( const std::string& /*pFilename*/Filename, std::string& pFileContent ) { //std::ifstream file( pFilename.c_str(), std::ios::in ); //if ( file ) //{ // // Initialize a string to store file content // file.seekg( 0, std::ios::end ); // pFileContent.resize( file.tellg() ); // file.seekg( 0, std::ios::beg ); // // Read file content // file.read( &pFileContent[ 0 ], pFileContent.size() ); // // Close file // file.close(); // return true; //} //else //{ // // LOG // // ... //} std::string Result; std::ifstream Stream(Filename.c_str()); if ( !Stream.is_open() ) { //return Result; pFileContent = Result; return false; } Stream.seekg(0, std::ios::end); Result.reserve(Stream.tellg()); Stream.seekg(0, std::ios::beg); Result.assign( (std::istreambuf_iterator<char>(Stream)), std::istreambuf_iterator<char>()); //return Result; pFileContent = Result; return true; //return false; } /****************************************************************************** * Tell whether or not pipeline has a given type of shader * * @param pShaderType the type of shader to test * * @return a flag telling whether or not pipeline has a given type of shader ******************************************************************************/ bool PtShaderProgram::hasShaderType( ShaderType pShaderType ) const { bool result = false; GLuint shader = 0; switch ( pShaderType ) { case ShaderType::eVertexShader: shader = _vertexShader; break; case ShaderType::eTesselationControlShader: shader = _tesselationControlShader; break; case ShaderType::eTesselationEvaluationShader: shader = _tesselationEvaluationShader; break; case ShaderType::eGeometryShader: shader = _geometryShader; break; case ShaderType::eFragmentShader: shader = _fragmentShader; break; case ShaderType::eComputeShader: shader = _computeShader; break; default: assert( false ); break; } return ( shader != 0 ); } /****************************************************************************** * Get the source code associated to a given type of shader * * @param pShaderType the type of shader * * @return the associated shader source code ******************************************************************************/ std::string PtShaderProgram::getShaderSourceCode( ShaderType pShaderType ) const { std::string shaderSourceCode( "" ); switch ( pShaderType ) { case ShaderType::eVertexShader: shaderSourceCode = _vertexShaderSourceCode; break; case ShaderType::eTesselationControlShader: shaderSourceCode = _tesselationControlShaderSourceCode; break; case ShaderType::eTesselationEvaluationShader: shaderSourceCode = _tesselationEvaluationShaderSourceCode; break; case ShaderType::eGeometryShader: shaderSourceCode = _geometryShaderSourceCode; break; case ShaderType::eFragmentShader: shaderSourceCode = _fragmentShaderSourceCode; break; case ShaderType::eComputeShader: shaderSourceCode = _computeShaderSourceCode; break; default: assert( false ); break; } return shaderSourceCode; } /****************************************************************************** * Get the filename associated to a given type of shader * * @param pShaderType the type of shader * * @return the associated shader filename ******************************************************************************/ std::string PtShaderProgram::getShaderFilename( ShaderType pShaderType ) const { std::string shaderFilename( "" ); switch ( pShaderType ) { case ShaderType::eVertexShader: shaderFilename = _vertexShaderFilename; break; case ShaderType::eTesselationControlShader: shaderFilename = _tesselationControlShaderFilename; break; case ShaderType::eTesselationEvaluationShader: shaderFilename = _tesselationEvaluationShaderFilename; break; case ShaderType::eGeometryShader: shaderFilename = _geometryShaderFilename; break; case ShaderType::eFragmentShader: shaderFilename = _fragmentShaderFilename; break; case ShaderType::eComputeShader: shaderFilename = _computeShaderFilename; break; default: assert( false ); break; } return shaderFilename; } /****************************************************************************** * ... * * @param pShaderType the type of shader * * @return ... ******************************************************************************/ bool PtShaderProgram::reloadShader( ShaderType pShaderType ) { if ( ! hasShaderType( pShaderType ) ) { // LOG // ... return false; } // Retrieve file content std::string shaderSourceCode; std::string shaderFilename = getShaderFilename( pShaderType ); bool isReadFileOK = getFileContent( shaderFilename, shaderSourceCode ); if ( ! isReadFileOK ) { // LOG // ... return false; } GLuint shader = 0; switch ( pShaderType ) { case ShaderType::eVertexShader: shader = _vertexShader; break; case ShaderType::eTesselationControlShader: shader = _tesselationControlShader; break; case ShaderType::eTesselationEvaluationShader: shader = _tesselationEvaluationShader; break; case ShaderType::eGeometryShader: shader = _geometryShader; break; case ShaderType::eFragmentShader: shader = _fragmentShader; break; case ShaderType::eComputeShader: shader = _computeShader; break; default: break; } // Check shader creation error if ( shader == 0 ) { // LOG // ... return false; } // Replace source code in shader object const char* source = shaderSourceCode.c_str(); glShaderSource( shader, 1, &source, NULL ); //int length = shaderSourceCode.size(); //glShaderSource(shader, 1, &source, &length ); // Compile shader object glCompileShader( shader ); // Check compilation status GLint compileStatus; glGetShaderiv( shader, GL_COMPILE_STATUS, &compileStatus ); if ( compileStatus == GL_FALSE ) { // LOG // ... GLint logInfoLength = 0; glGetShaderiv( shader, GL_INFO_LOG_LENGTH, &logInfoLength ); if ( logInfoLength > 0 ) { // Return information log for shader object GLchar* infoLog = new GLchar[ logInfoLength ]; GLsizei length = 0; glGetShaderInfoLog( shader, logInfoLength, &length, infoLog ); // LOG std::cout << "\nPtShaderProgram::reloadShader() - compilation ERROR" << std::endl; std::cout << infoLog << std::endl; delete[] infoLog; } return false; } // Link program // // - first, unliked the program _linked = false; if ( ! link() ) { return false; } return true; } /****************************************************************************** * Register uniform names ******************************************************************************/ void PtShaderProgram::registerUniforms( const std::vector< std::string >& pUniformNames ) { // Store uniforms info (after shader program link() step) for ( const auto& uniformName : pUniformNames ) { GLint uniformLocation = glGetUniformLocation( _program, uniformName.c_str() ); if ( uniformLocation >= 0 ) { mUniformLocations[ uniformName ] = uniformLocation; } } }
19,479
C++
.cpp
656
27.010671
139
0.602198
ASTex-ICube/semiproctex
39
8
2
LGPL-2.1
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,920
PtCamera.cpp
ASTex-ICube_semiproctex/PPTBF_Structures_Src/PtGraphics/PtCamera.cpp
/* * Publication: Semi-Procedural Textures Using Point Process Texture Basis Functions * Authors: anonymous * * Code author: Pascal Guehl * * anonymous * anonymous */ /** * @version 1.0 */ #include "PtCamera.h" /****************************************************************************** ******************************* INCLUDE SECTION ****************************** ******************************************************************************/ // GL #include <glad/glad.h> // STL #include <iostream> // glm #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #include <glm/gtx/rotate_vector.hpp> /****************************************************************************** ****************************** NAMESPACE SECTION ***************************** ******************************************************************************/ // Project using namespace PtGraphics; // STL using namespace std; /****************************************************************************** ************************* DEFINE AND CONSTANT SECTION ************************ ******************************************************************************/ /****************************************************************************** ***************************** TYPE DEFINITION ******************************** ******************************************************************************/ /****************************************************************************** ***************************** METHOD DEFINITION ****************************** ******************************************************************************/ // Example // https://gitlab.com/pteam/korvins-qtbase/blob/6f7bc2a7074b7f8c9dacd997d4af597396bbc8d0/examples/opengl/qopenglwindow/main.cpp // Explanations // https://blog.qt.io/blog/2014/11/20/qt-weekly-20-completing-the-offering-qopenglwindow-and-qrasterwindow/ /****************************************************************************** * Default constructor ******************************************************************************/ PtCamera::PtCamera() { mEye = glm::vec3( 0.f, 0.f, 1.f ); mFront = glm::vec3( 0.f, 0.f, -1.f ); mUp = glm::vec3( 0.f, 1.f, 0.f ); mFovY = 45.f; mAspect = 1.f; mLeft = -1.f; mRight = 1.f; mBottom = -1.f; mTop = 1.f; mZNear = 0.1f; mZFar = 100.f; mSensitivity = 0.1f; mCameraType = ePerspective; } /****************************************************************************** * Destructor ******************************************************************************/ PtCamera::~PtCamera() { } /****************************************************************************** * Tilt ******************************************************************************/ void PtCamera::tilt( float pValue ) { const glm::vec3 right = glm::normalize( glm::cross( mFront, mUp ) ); mFront = glm::rotate( mFront, pValue, right ); } /****************************************************************************** * Pan (i.e. yaw) ******************************************************************************/ void PtCamera::pan( float pValue ) { mFront = glm::rotate( mFront, pValue, mUp ); } /****************************************************************************** * Dolly ******************************************************************************/ void PtCamera::dolly( float pValue ) { mEye += mSensitivity * pValue * mFront; } /****************************************************************************** * Truck ******************************************************************************/ void PtCamera::truck( float pValue ) { mEye += glm::normalize( glm::cross( mFront, mUp ) ) * pValue * mSensitivity; } /****************************************************************************** * Pedestal ******************************************************************************/ void PtCamera::pedestal( float pValue ) { mEye += pValue * mSensitivity * mUp; } /****************************************************************************** * Zoom ******************************************************************************/ void PtCamera::zoom( float pValue ) { const float cMaxFovY = 120.f; if ( mFovY >= 1.f && mFovY <= cMaxFovY ) { mFovY += mSensitivity * pValue; } if ( mFovY <= 1.f ) { mFovY = 1.f; } if ( mFovY >= cMaxFovY ) { mFovY = cMaxFovY; } } /****************************************************************************** * ... ******************************************************************************/ void PtCamera::setEye( const glm::vec3& pPosition ) { mEye = pPosition; } /****************************************************************************** * ... ******************************************************************************/ void PtCamera::setFront( const glm::vec3& pPosition ) { mFront = pPosition; } /****************************************************************************** * ... ******************************************************************************/ void PtCamera::setUp( const glm::vec3& pDirection ) { mUp = pDirection; } /****************************************************************************** * ... ******************************************************************************/ float PtCamera::getFovY() const { return mFovY; } /****************************************************************************** * ... ******************************************************************************/ void PtCamera::setFovY( float pValue ) { mFovY = pValue; } /****************************************************************************** * ... ******************************************************************************/ float PtCamera::getAspect() const { return mAspect; } /****************************************************************************** * ... ******************************************************************************/ void PtCamera::setAspect( float pValue ) { mAspect = pValue; } /****************************************************************************** * ... ******************************************************************************/ float PtCamera::getLeft() const { return mLeft; } /****************************************************************************** * ... ******************************************************************************/ void PtCamera::setLeft( float pValue ) { mLeft = pValue; } /****************************************************************************** * ... ******************************************************************************/ float PtCamera::getRight() const { return mRight; } /****************************************************************************** * ... ******************************************************************************/ void PtCamera::setRight( float pValue ) { mRight = pValue; } /****************************************************************************** * ... ******************************************************************************/ float PtCamera::getBottom() const { return mBottom; } /****************************************************************************** * ... ******************************************************************************/ void PtCamera::setBottom( float pValue ) { mBottom = pValue; } /****************************************************************************** * ... ******************************************************************************/ float PtCamera::getTop() const { return mTop; } /****************************************************************************** * ... ******************************************************************************/ void PtCamera::setTop( float pValue ) { mTop = pValue; } /****************************************************************************** * ... ******************************************************************************/ float PtCamera::getZNear() const { return mZNear; } /****************************************************************************** * ... ******************************************************************************/ void PtCamera::setZNear( float pValue ) { mZNear = pValue; } /****************************************************************************** * ... ******************************************************************************/ float PtCamera::getZFar() const { return mZFar; } /****************************************************************************** * ... ******************************************************************************/ void PtCamera::setZFar( float pValue ) { mZFar = pValue; } /****************************************************************************** * ... ******************************************************************************/ float PtCamera::getSensitivity() const { return mSensitivity; } /****************************************************************************** * ... ******************************************************************************/ void PtCamera::setSensitivity( float pValue ) { mSensitivity = pValue; } /****************************************************************************** * ... ******************************************************************************/ glm::mat4 PtCamera::getViewMatrix() const { return glm::lookAt( mEye, mEye + mFront, mUp ); } /****************************************************************************** * ... ******************************************************************************/ glm::mat4 PtCamera::getProjectionMatrix() const { if ( mCameraType == eOrthographic ) { return glm::ortho( mLeft, mRight, mBottom, mTop ); } return glm::perspective( mFovY, mAspect, mZNear, mZFar ); } /****************************************************************************** * ... ******************************************************************************/ void PtCamera::setCameraType( ECameraType pType ) { mCameraType = pType; }
10,171
C++
.cpp
296
32.658784
127
0.257437
ASTex-ICube/semiproctex
39
8
2
LGPL-2.1
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,921
PtGraphicsMeshManager.cpp
ASTex-ICube_semiproctex/PPTBF_Structures_Src/PtGraphics/PtGraphicsMeshManager.cpp
/* * Publication: Semi-Procedural Textures Using Point Process Texture Basis Functions * Authors: anonymous * * Code author: Pascal Guehl * * anonymous * anonymous */ /** * @version 1.0 */ #include "PtGraphicsMeshManager.h" /****************************************************************************** ******************************* INCLUDE SECTION ****************************** ******************************************************************************/ // Project #include "PtShaderProgram.h" #include "PtCamera.h" #include <PtEnvironment.h> // glm #include <glm/gtc/matrix_transform.hpp> #include <glm/gtx/transform.hpp> #include <glm/gtc/matrix_inverse.hpp> // System #include <cassert> #include <cstddef> // STL #include <iostream> #include <algorithm> #include <functional> #include <numeric> #include <iomanip> #include <vector> /****************************************************************************** ****************************** NAMESPACE SECTION ***************************** ******************************************************************************/ // Project using namespace PtGraphics; /****************************************************************************** ************************* DEFINE AND CONSTANT SECTION ************************ ******************************************************************************/ /****************************************************************************** ***************************** TYPE DEFINITION ******************************** ******************************************************************************/ /****************************************************************************** ***************************** METHOD DEFINITION ****************************** ******************************************************************************/ /****************************************************************************** * Constructor ******************************************************************************/ PtGraphicsMeshManager::PtGraphicsMeshManager() : mVAO( 0 ) , mPositionVBO( 0 ) , mTextureCoordinateVBO( 0 ) , mNormalVBO( 0 ) , mElementArrayBuffer( 0 ) , mNbMeshIndices( 0 ) , mModelMatrix( glm::mat4( 1.f ) ) , mUseMaterial( false ) , mBump( 1.f ) , mMeshType( MeshType::eGridMesh ) , mColormapIndex( -1 ) { mShaderProgram = new PtShaderProgram(); mShaderProgram2 = new PtShaderProgram(); } /****************************************************************************** * Destructor ******************************************************************************/ PtGraphicsMeshManager::~PtGraphicsMeshManager() { delete mShaderProgram; mShaderProgram = nullptr; delete mShaderProgram2; mShaderProgram2 = nullptr; } /****************************************************************************** * Initialize ******************************************************************************/ void PtGraphicsMeshManager::initialize() { initializeGraphicsResources(); initializeShaderPrograms(); } /****************************************************************************** * Finalize ******************************************************************************/ void PtGraphicsMeshManager::finalize() { } /****************************************************************************** * Initialize per-pixel parameters graphics resources * * @return a flag telling whether or not it succeeds ******************************************************************************/ bool PtGraphicsMeshManager::initializeGraphicsResources() { return true; } /****************************************************************************** * Initialize per-pixel parameters graphics resources * * @return a flag telling whether or not it succeeds ******************************************************************************/ bool PtGraphicsMeshManager::finalizeGraphicsResources() { // Release graphics resources if ( mVAO ) { glDeleteVertexArrays( 1, &mVAO ); } if ( mPositionVBO ) { glDeleteBuffers( 1, &mPositionVBO ); } if ( mTextureCoordinateVBO ) { glDeleteBuffers( 1, &mTextureCoordinateVBO ); } if ( mNormalVBO ) { glDeleteBuffers( 1, &mNormalVBO ); } if ( mElementArrayBuffer ) { glDeleteBuffers( 1, &mElementArrayBuffer ); } return true; } /****************************************************************************** * ... ******************************************************************************/ void PtGraphicsMeshManager::setPPTBFTexture( const GLuint pTexture ) { mPPTBFTexture = pTexture; } /****************************************************************************** * Set the mesh type ******************************************************************************/ void PtGraphicsMeshManager::setMeshType( const PtGraphicsMeshManager::MeshType pMeshType ) { switch ( pMeshType ) { case MeshType::eGridMesh: generateGrid( mUseMaterial ? 1024 : 4 ); break; case MeshType::eWaveMesh: generateWave( mUseMaterial ? 1024 : 64 ); break; case MeshType::eCylinderMesh: generateCylinder( mUseMaterial ? 1024 : 64 ); break; case MeshType::eTorusMesh: generateTorus( mUseMaterial ? 1024 : 64 ); break; case MeshType::eSphereMesh: generateSphere( mUseMaterial ? 1024 : 64 ); break; default: generateGrid( mUseMaterial ? 1024 : 4 ); break; } mMeshType = pMeshType; } /****************************************************************************** * Initialize shader program ******************************************************************************/ bool PtGraphicsMeshManager::initializeShaderPrograms() { bool statusOK = false; /*delete mShaderProgram; mShaderProgram = nullptr; mShaderProgram = new PtShaderProgram();*/ // Global variables const std::string shaderPath = Pt::PtEnvironment::mShaderPath + std::string( "/" ); PtShaderProgram* shaderProgram = nullptr; PtShaderProgram::TShaderList shaders; std::string shaderFilename; std::vector< std::string > uniforms; // Rendering: fullscreen triangle // Initialize shader program shaderProgram = mShaderProgram; shaderProgram->finalize(); shaderProgram->initialize(); shaderProgram->setName( "meshRenderer" ); shaderProgram->setInfo( "Mesh Renderer" ); // - path shaders.clear(); shaderFilename = shaderPath + "meshRendering_vert.glsl"; shaders.push_back( std::make_pair( PtShaderProgram::ShaderType::eVertexShader, shaderFilename ) ); shaderFilename = shaderPath + "meshRendering_frag.glsl"; shaders.push_back( std::make_pair( PtShaderProgram::ShaderType::eFragmentShader, shaderFilename ) ); statusOK = shaderProgram->initializeProgram( shaders ); // Store uniforms info (after shader program link() step) uniforms.clear(); uniforms.push_back( "uProjectionMatrix" ); uniforms.push_back( "uViewMatrix" ); uniforms.push_back( "uModelMatrix" ); uniforms.push_back( "uNormalMatrix" ); uniforms.push_back( "uPPTBFTexture" ); uniforms.push_back( "uColormapIndex" ); shaderProgram->registerUniforms( uniforms ); // Rendering: fullscreen triangle // Initialize shader program shaderProgram = mShaderProgram2; shaderProgram->finalize(); shaderProgram->initialize(); shaderProgram->setName( "meshRenderer" ); shaderProgram->setInfo( "Mesh Renderer" ); // - path shaders.clear(); shaderFilename = shaderPath + "meshRendering_bump_vert.glsl"; shaders.push_back( std::make_pair( PtShaderProgram::ShaderType::eVertexShader, shaderFilename ) ); shaderFilename = shaderPath + "meshRendering_bump_frag.glsl"; shaders.push_back( std::make_pair( PtShaderProgram::ShaderType::eFragmentShader, shaderFilename ) ); statusOK = shaderProgram->initializeProgram( shaders ); // Store uniforms info (after shader program link() step) uniforms.clear(); uniforms.push_back( "uProjectionMatrix" ); uniforms.push_back( "uViewMatrix" ); uniforms.push_back( "uModelMatrix" ); uniforms.push_back( "uNormalMatrix" ); uniforms.push_back( "uPPTBFTexture" ); uniforms.push_back( "hmax" ); uniforms.push_back( "uColormapIndex" ); shaderProgram->registerUniforms( uniforms ); return statusOK; } /****************************************************************************** * Render mesh ******************************************************************************/ void PtGraphicsMeshManager::render( const PtCamera* const pCamera ) { // Set shader program PtShaderProgram* shaderProgram; if ( ! useMaterial() ) { shaderProgram = mShaderProgram; } else { shaderProgram = mShaderProgram2; } shaderProgram->use(); { // Set texture(s) // - PPTBF data glBindTextureUnit( 0/*unit*/, mPPTBFTexture ); // Set uniform(s) // - camera const glm::mat4 viewMatrix = pCamera->getViewMatrix(); const glm::mat4 projectionMatrix = pCamera->getProjectionMatrix(); shaderProgram->set( viewMatrix, "uViewMatrix" ); shaderProgram->set( projectionMatrix, "uProjectionMatrix" ); // - model transform shaderProgram->set( mModelMatrix, "uModelMatrix" ); // - appearance if ( useMaterial() ) { shaderProgram->set( glm::mat3( glm::inverseTranspose( viewMatrix ) ), "uNormalMatrix" ); shaderProgram->set( mBump, "hmax" ); } shaderProgram->set( getColormapIndex(), "uColormapIndex" ); // - PPTBF data shaderProgram->set( 0, "uPPTBFTexture" ); // Note: this uniform never changes => can be set after shaderprogram::link() // Set vertex array glBindVertexArray( mVAO ); // Draw command(s) //glPolygonMode( GL_FRONT_AND_BACK, GL_LINE ); glDrawElements( GL_TRIANGLES, mNbMeshIndices, GL_UNSIGNED_INT, 0 ); //glPolygonMode( GL_FRONT_AND_BACK, GL_FILL ); } PtShaderProgram::unuse(); } /****************************************************************************** * Render baisc (i.e. no shader) ******************************************************************************/ void PtGraphicsMeshManager::renderBasic() { // Set vertex array glBindVertexArray( mVAO ); // Draw command(s) glDrawElements( GL_TRIANGLES, mNbMeshIndices, GL_UNSIGNED_INT, 0 ); } /****************************************************************************** * Generate a grid mesh ******************************************************************************/ void PtGraphicsMeshManager::generateGrid( const unsigned int n ) { assert( n > 0 ); // Release graphics resources finalizeGraphicsResources(); // Build geometry const unsigned int n1 = n - 1; std::vector< glm::vec3 > pos; std::vector< glm::vec2 > tc; std::vector< glm::vec3 > norm; pos.reserve( n * n ); tc.reserve( n * n ); norm.reserve( n * n ); for ( unsigned int j = 0; j < n; ++j ) { for ( unsigned int i = 0; i < n; ++i ) { const float u = ( 1.f / n1 ) * i; const float v = ( 1.f / n1 ) * j; tc.push_back( glm::vec2( u, v ) ); pos.push_back( glm::vec3( ( u - 0.5f ) * 2.f, ( v - 0.5f ) * 2.f, 0.f ) ); norm.push_back( glm::vec3( 0.f, 0.f, 1.f ) ); } } // Build topology std::vector< unsigned int > indices; indices.reserve( 6 * (n - 1)*(n - 1) ); unsigned int last = 0; for ( unsigned int j = 1; j < n; ++j ) { for ( unsigned int i = 1; i < n; ++i ) { unsigned int k = j*n + i; // push quad indices.push_back(k); indices.push_back(k - n - 1); indices.push_back(k - n); indices.push_back(k - n - 1); indices.push_back(k); indices.push_back(k - 1); } } // Store number of indices (for rendering) mNbMeshIndices = indices.size(); // Set graphics resources setGraphicsResources( pos, tc, norm, indices ); } /****************************************************************************** * Generate a wave mesh ******************************************************************************/ void PtGraphicsMeshManager::generateWave( const unsigned int n ) { assert( n > 0 ); // Release graphics resources finalizeGraphicsResources(); // Build geometry const unsigned int n1 = n - 1; std::vector< glm::vec3 > pos; std::vector< glm::vec2 > tc; std::vector< glm::vec3 > norm; pos.reserve( n * n ); tc.reserve( n * n ); norm.reserve( n * n ); for ( unsigned int j = 0; j < n; ++j ) { const float v = (1.0/n1)*j; for( unsigned int i = 0; i < n; ++i ) { const float u = (1.0/n1)*i; tc.push_back( glm::vec2( u, v ) ); const float x = ( u - 0.5 ) * 2; const float y = ( v - 0.5 ) * 2; const float r = glm::sqrt( x * x + y * y ); const float h = 0.2f * ( 1.f - r / 2.f ) * glm::sin( glm::half_pi< float >() + r * 8.f ); pos.push_back( glm::vec3( x, y, h ) ); const float dh = -0.2/2 * glm::sin( glm::half_pi< float >() + r * 8.f ) + 0.2 * (1-r/2) * 8.f * glm::cos( glm::half_pi< float >() + r * 8.f ); const glm::vec3 n = glm::vec3( -x/r*dh, -y/r*dh, 1.f ); norm.push_back( glm::normalize( n ) ); } } // Build topology std::vector< unsigned int > indices; indices.reserve( 6 * (n - 1)*(n - 1) ); unsigned int last = 0; for ( unsigned int j = 1; j < n; ++j ) { for ( unsigned int i = 1; i < n; ++i ) { unsigned int k = j*n + i; // push quad indices.push_back(k); indices.push_back(k - n - 1); indices.push_back(k - n); indices.push_back(k - n - 1); indices.push_back(k); indices.push_back(k - 1); } } // Store number of indices (for rendering) mNbMeshIndices = indices.size(); // Set graphics resources setGraphicsResources( pos, tc, norm, indices ); } /****************************************************************************** * Generate a cylinder mesh ******************************************************************************/ void PtGraphicsMeshManager::generateCylinder( const unsigned int n ) { assert( n > 0 ); // Release graphics resources finalizeGraphicsResources(); // Build geometry const unsigned int n1 = n - 1; std::vector< glm::vec3 > pos; std::vector< glm::vec2 > tc; std::vector< glm::vec3 > norm; pos.reserve( n * n ); tc.reserve( n * n ); norm.reserve( n * n ); std::vector< glm::vec3 > cpos; std::vector< glm::vec3 > cnorm; cpos.reserve( n ); cnorm.reserve( n ); for( unsigned int i = 0; i < n; ++i ) { const float alpha = ( (1.0/n1) * i ) * 2 * glm::pi< float >(); glm::vec3 p = glm::vec3( 0.f, glm::cos(alpha), glm::sin(alpha) ); cnorm.push_back( p ); cpos.push_back( p * 0.8f ); } for ( unsigned int j = 0; j < n; ++j ) { //let tr = translate( -1+2/n1*j, 0, 0 ); const float t = -1 + ( 2.f / n1 ) * j; glm::mat4 tr = glm::translate( glm::mat4( 1.0f ), glm::vec3( t, 0.f, 0.f ) ); //let ntr = tr.inverse3transpose(); glm::mat4 ntr = glm::transpose( glm::inverse( tr ) ); const float v = (1.0/n1) * j; for ( unsigned int i = 0; i < n; ++i ) { const float u = (1.0/n1) * i; tc.push_back( glm::vec2( u, v ) ); //pos.push_back( tr.transform( cpos.get_vec3( i ) ) ); pos.push_back( glm::vec3( tr * glm::vec4( cpos[ i ], 1.f ) ) ); //norm.push_back( ntr.mult( cnorm.get_vec3( i ) ) ); norm.push_back( glm::vec3( ntr * glm::vec4( cnorm[ i ], 0.f ) ) ); } } // Build topology std::vector< unsigned int > indices; indices.reserve( 6 * (n - 1)*(n - 1) ); unsigned int last = 0; for ( unsigned int j = 1; j < n; ++j ) { for ( unsigned int i = 1; i < n; ++i ) { unsigned int k = j*n + i; // push quad indices.push_back(k); indices.push_back(k - n - 1); indices.push_back(k - n); indices.push_back(k - n - 1); indices.push_back(k); indices.push_back(k - 1); } } // Store number of indices (for rendering) mNbMeshIndices = indices.size(); // Set graphics resources setGraphicsResources( pos, tc, norm, indices ); } /****************************************************************************** * Generate a torus mesh ******************************************************************************/ void PtGraphicsMeshManager::generateTorus( const unsigned int n ) { assert( n > 0 ); // Release graphics resources finalizeGraphicsResources(); // Build geometry const unsigned int n1 = n - 1; std::vector< glm::vec3 > pos; std::vector< glm::vec2 > tc; std::vector< glm::vec3 > norm; pos.reserve( n * n ); tc.reserve( n * n ); norm.reserve( n * n ); std::vector< glm::vec3 > cpos; std::vector< glm::vec3 > cnorm; cpos.reserve( n ); cnorm.reserve( n ); for( unsigned int i = 0; i <n; ++i ) { const float alpha = ( (1.0/n1) * i ) * 2.f * glm::pi< float >(); glm::vec3 p = glm::vec3( 0, glm::sin( alpha ), glm::cos( alpha ) ); cnorm.push_back( p ); cpos.push_back( p * 0.4f ); } for( unsigned int j = 0; j < n; ++j ) { //let tr = rotate( (360/n1)*j, Vec3(0,0,1) ).mult(translate(0,0.6,0)); //glm::mat4 tr = glm::translate( glm::rotate( glm::mat4( 1.f ), (360.f / n1) * j, glm::vec3( 0.f, 0.f, 1.f ) ), glm::vec3( 0.f, 0.6f, 0.f ) ); const glm::mat4 t = glm::translate( glm::mat4( 1.f ), glm::vec3( 0.f, 0.6f, 0.f ) ); const glm::mat4 r = glm::rotate( ( 1.f / n1 ) * j * 2.f * glm::pi< float >(), glm::vec3( 0.f, 0.f, 1.f ) ); const glm::mat4 tr = r * t; //let ntr = tr.inverse3transpose(); glm::mat4 ntr = glm::transpose( glm::inverse( tr ) ); const float v = (1.0/n1) * j; for ( unsigned int i = 0; i < n; ++i ) { const float u = (1.0/n1) * i; tc.push_back( glm::vec2(u,v) ); //pos.push_back( tr.transform(cpos.get_vec3(i)) ); pos.push_back( glm::vec3( tr * glm::vec4( cpos[ i ], 1.f ) ) ); //norm.push_back( ntr.mult(cnorm.get_vec3(i)) ); norm.push_back( glm::vec3( ntr * glm::vec4( cnorm[ i ], 0.f ) ) ); } } // Build topology std::vector< unsigned int > indices; indices.reserve( 6 * (n - 1)*(n - 1) ); unsigned int last = 0; for ( unsigned int j = 1; j < n; ++j ) { for ( unsigned int i = 1; i < n; ++i ) { unsigned int k = j*n + i; // push quad indices.push_back(k); indices.push_back(k - n - 1); indices.push_back(k - n); indices.push_back(k - n - 1); indices.push_back(k); indices.push_back(k - 1); } } // Store number of indices (for rendering) mNbMeshIndices = indices.size(); // Set graphics resources setGraphicsResources( pos, tc, norm, indices ); } /****************************************************************************** * Generate a sphere mesh ******************************************************************************/ void PtGraphicsMeshManager::generateSphere( const unsigned int n ) { assert( n > 0 ); // Release graphics resources finalizeGraphicsResources(); // Build geometry const unsigned int n1 = n - 1; std::vector< glm::vec3 > pos; std::vector< glm::vec2 > tc; std::vector< glm::vec3 > norm; pos.reserve( n * n ); tc.reserve( n * n ); norm.reserve( n * n ); const float a1 = glm::pi< float >() / n1; const float a2 = 2.f * glm::pi< float >() / n1; for ( unsigned int j = 0; j < n; ++j ) { const float angle = -glm::half_pi< float >() + a1*j; const float z = glm::sin( angle ); const float radius = glm::cos( angle ); const float v = (1.0/n1) * j; for ( unsigned int i = 0; i < n; ++i ) { const float u = (1.0/n1) * i; tc.push_back( glm::vec2(u,v) ); const float beta = a2*i; glm::vec3 p = glm::vec3( radius * glm::cos(beta), radius * glm::sin(beta), z ); pos.push_back( p ); norm.push_back( p ); } } // Build topology std::vector< unsigned int > indices; indices.reserve( 6 * (n - 1)*(n - 1) ); unsigned int last = 0; for ( unsigned int j = 1; j < n; ++j ) { for ( unsigned int i = 1; i < n; ++i ) { unsigned int k = j*n + i; // push quad indices.push_back(k); indices.push_back(k - n - 1); indices.push_back(k - n); indices.push_back(k - n - 1); indices.push_back(k); indices.push_back(k - 1); } } // Store number of indices (for rendering) mNbMeshIndices = indices.size(); // Set graphics resources setGraphicsResources( pos, tc, norm, indices ); } /****************************************************************************** * Set graphics resources ******************************************************************************/ void PtGraphicsMeshManager::setGraphicsResources( const std::vector< glm::vec3 >& pPositions, const std::vector< glm::vec2 >& pTextureCoordinates, const std::vector< glm::vec3 >& pNormals, const std::vector< unsigned int >& pIndices ) { const bool usePositions = ! pPositions.empty(); const bool useTextureCoordinates = ! pTextureCoordinates.empty(); const bool useNormals = ! pNormals.empty(); const bool useIndices = ! pIndices.empty(); // Create buffer objects if ( usePositions ) { glCreateBuffers( 1, &mPositionVBO ); } if ( useTextureCoordinates ) { glCreateBuffers( 1, &mTextureCoordinateVBO ); } if ( useNormals ) { glCreateBuffers( 1, &mNormalVBO ); } if ( useIndices ) { glCreateBuffers( 1, &mElementArrayBuffer ); } // Creates and initializes buffer objects's immutable data store if ( usePositions ) { glNamedBufferStorage( mPositionVBO, static_cast< GLsizeiptr >( sizeof( glm::vec3 ) * pPositions.size() ), pPositions.data(), 0/*static data buffer*/ ); } if ( useTextureCoordinates ) { glNamedBufferStorage( mTextureCoordinateVBO, static_cast< GLsizeiptr >( sizeof( glm::vec2 ) * pTextureCoordinates.size() ), pTextureCoordinates.data(), 0/*static data buffer*/ ); } if ( useNormals ) { glNamedBufferStorage( mNormalVBO, static_cast< GLsizeiptr >( sizeof( glm::vec3 ) * pNormals.size() ), pNormals.data(), 0/*static data buffer*/ ); } if ( useIndices ) { glNamedBufferStorage( mElementArrayBuffer, static_cast< GLsizeiptr >( sizeof( unsigned int ) * pIndices.size() ), pIndices.data(), 0/*static data buffer*/ ); } // Create vertex array object glCreateVertexArrays( 1, &mVAO ); // Bind buffers to vertex buffer bind points if ( usePositions ) { glVertexArrayVertexBuffer( mVAO, 0/*binding index*/, mPositionVBO, 0/*offset*/, sizeof( glm::vec3 )/*stride*/ ); } if ( useTextureCoordinates ) { glVertexArrayVertexBuffer( mVAO, 1/*binding index*/, mTextureCoordinateVBO, 0/*offset*/, sizeof( glm::vec2 )/*stride*/ ); } if ( useNormals ) { glVertexArrayVertexBuffer( mVAO, 2/*binding index*/, mNormalVBO, 0/*offset*/, sizeof( glm::vec3 )/*stride*/ ); } // Configures element array buffer binding of a vertex array object if ( useIndices ) { glVertexArrayElementBuffer( mVAO, mElementArrayBuffer ); } // Enable generic vertex attribute arrays if ( usePositions ) { glEnableVertexArrayAttrib( mVAO, 0/*index*/ ); } if ( useTextureCoordinates ) { glEnableVertexArrayAttrib( mVAO, 1/*index*/ ); } if ( useNormals ) { glEnableVertexArrayAttrib( mVAO, 2/*index*/ ); } // Specify the organization of vertex arrays if ( usePositions ) { glVertexArrayAttribFormat( mVAO, 0/*attribindex*/, 3/*size*/, GL_FLOAT, GL_FALSE/*normalized*/, 0/*relativeoffset*/ ); } if ( useTextureCoordinates ) { glVertexArrayAttribFormat( mVAO, 1/*attribindex*/, 2/*size*/, GL_FLOAT, GL_FALSE/*normalized*/, 0/*relativeoffset*/ ); } if ( useNormals ) { glVertexArrayAttribFormat( mVAO, 2/*attribindex*/, 3/*size*/, GL_FLOAT, GL_FALSE/*normalized*/, 0/*relativeoffset*/ ); } // Associate a vertex attribute and a vertex buffer binding for a vertex array object if ( usePositions ) { glVertexArrayAttribBinding( mVAO, 0/*attribindex*/, 0/*bindingindex*/ ); } if ( useTextureCoordinates ) { glVertexArrayAttribBinding( mVAO, 1/*attribindex*/, 1/*bindingindex*/ ); } if ( useNormals ) { glVertexArrayAttribBinding( mVAO, 2/*attribindex*/, 2/*bindingindex*/ ); } }
23,482
C++
.cpp
693
31.427128
180
0.562238
ASTex-ICube/semiproctex
39
8
2
LGPL-2.1
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,922
PtGraphicsLibrary.cpp
ASTex-ICube_semiproctex/PPTBF_Structures_Src/PtGraphics/PtGraphicsLibrary.cpp
/* * Publication: Semi-Procedural Textures Using Point Process Texture Basis Functions * Authors: anonymous * * Code author: Pascal Guehl * * anonymous * anonymous */ /** * @version 1.0 */ #include "PtGraphicsLibrary.h" /****************************************************************************** ******************************* INCLUDE SECTION ****************************** ******************************************************************************/ // Project #include <PtModelLibrary.h> // GsGraphics //#include "GsGraphics/GsAssetResourceManager.h" /****************************************************************************** ****************************** NAMESPACE SECTION ***************************** ******************************************************************************/ // Project using namespace PtGraphics; /****************************************************************************** ************************* DEFINE AND CONSTANT SECTION ************************ ******************************************************************************/ /****************************************************************************** ***************************** TYPE DEFINITION ******************************** ******************************************************************************/ bool PtGraphicsLibrary::mIsInitialized = false; /****************************************************************************** ***************************** METHOD DEFINITION ****************************** ******************************************************************************/ /****************************************************************************** * Main GsGraphics module initialization method ******************************************************************************/ bool PtGraphicsLibrary::initialize( const char* const pWorkingDirectory ) { if ( mIsInitialized ) { return true; } bool statusOK = Pt::PtDataModelLibrary::initialize( pWorkingDirectory ); if ( ! statusOK ) { return false; } // Load plugins //GsAssetResourceManager::get().loadPlugins(""); // Update flag mIsInitialized = true; return true; } /****************************************************************************** * Main GsGraphics module finalization method ******************************************************************************/ void PtGraphicsLibrary::finalize() { // Unload plugins //GsAssetResourceManager::get().unloadAll(); // Update flag mIsInitialized = false; }
2,562
C++
.cpp
65
37.446154
84
0.334812
ASTex-ICube/semiproctex
39
8
2
LGPL-2.1
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,923
PtGraphicsHistogram.cpp
ASTex-ICube_semiproctex/PPTBF_Structures_Src/PtGraphics/PtGraphicsHistogram.cpp
/* * Publication: Semi-Procedural Textures Using Point Process Texture Basis Functions * Authors: anonymous * * Code author: Pascal Guehl * * anonymous * anonymous */ /** * @version 1.0 */ #include "PtGraphicsHistogram.h" /****************************************************************************** ******************************* INCLUDE SECTION ****************************** ******************************************************************************/ // System #include <cassert> // STL #include <iostream> #include <numeric> #include <algorithm> // Project #include "PtPPTBF.h" #include "PtNoise.h" #include <PtEnvironment.h> /****************************************************************************** ****************************** NAMESPACE SECTION ***************************** ******************************************************************************/ // Project using namespace Pt; using namespace PtGraphics; /****************************************************************************** ************************* DEFINE AND CONSTANT SECTION ************************ ******************************************************************************/ /****************************************************************************** ***************************** TYPE DEFINITION ******************************** ******************************************************************************/ /****************************************************************************** ***************************** METHOD DEFINITION ****************************** ******************************************************************************/ /****************************************************************************** * Constructor ******************************************************************************/ PtGraphicsHistogram::PtGraphicsHistogram() : mShaderProgram( nullptr ) , mNbBins( 0 ) , mPPTBFFrameBuffer( 0 ) , mPPTBFTexture( 0 ) { mShaderProgram = new PtShaderProgram(); } /****************************************************************************** * Destructor ******************************************************************************/ PtGraphicsHistogram::~PtGraphicsHistogram() { // Reset graphics resources finalize(); delete mShaderProgram; mShaderProgram = nullptr; } /****************************************************************************** * Initialize ******************************************************************************/ void PtGraphicsHistogram::initialize( const int pNbBins ) { mNbBins = pNbBins; // Initialize framebuffer initializeFramebuffer(); // Initialize shader program initializeShaderProgram(); } /****************************************************************************** * Initialize framebuffer ******************************************************************************/ void PtGraphicsHistogram::initializeFramebuffer() { // Initialize texture "rnd_tab" glCreateTextures( GL_TEXTURE_2D, 1, &mPPTBFTexture ); // - set the texture wrapping/filtering options (on the currently bound texture object) glTextureParameteri( mPPTBFTexture, GL_TEXTURE_WRAP_S, /*GL_REPEAT*/GL_CLAMP_TO_EDGE ); glTextureParameteri( mPPTBFTexture, GL_TEXTURE_WRAP_T, /*GL_REPEAT*/GL_CLAMP_TO_EDGE ); glTextureParameteri( mPPTBFTexture, GL_TEXTURE_MIN_FILTER, /*GL_LINEAR*/GL_NEAREST ); glTextureParameteri( mPPTBFTexture, GL_TEXTURE_MAG_FILTER, /*GL_LINEAR*/GL_NEAREST ); // - set min/max level for completeness glTextureParameteri( mPPTBFTexture, GL_TEXTURE_BASE_LEVEL, 0 ); glTextureParameteri( mPPTBFTexture, GL_TEXTURE_MAX_LEVEL, 0 ); // - generate the texture glActiveTexture( GL_TEXTURE0 ); glBindTexture( GL_TEXTURE_2D, mPPTBFTexture ); glTexImage2D( GL_TEXTURE_2D, 0/*level*/, GL_R32F, mNbBins/*width*/, 1/*height*/, 0/*border*/, GL_RED, GL_FLOAT, nullptr ); //glTextureStorage2D( mPPTBFTexture, 1/*levels*/, GL_R32F, mNbBins/*width*/, 1/*height*/ ); //glTextureSubImage2D( mPPTBFTexture, 0/*level*/, 0/*xoffset*/, 0/*yoffset*/, mNbBins/*width*/, 1/*height*/, GL_RED, GL_FLOAT, nullptr ); // - reset device state //glBindTexture( GL_TEXTURE_2D, 0 ); // Configure framebuffer //glCreateFramebuffers( 1, &mPPTBFFrameBuffer ); //glNamedFramebufferTexture( mPPTBFFrameBuffer, GL_COLOR_ATTACHMENT0, mPPTBFTexture, 0/*level*/ ); //glDrawBuffer( GL_COLOR_ATTACHMENT0 ); //glNamedFramebufferDrawBuffer( mPPTBFFrameBuffer, GL_COLOR_ATTACHMENT0 ); glGenFramebuffers( 1, &mPPTBFFrameBuffer ); glBindFramebuffer( GL_FRAMEBUFFER, mPPTBFFrameBuffer ); glFramebufferTexture2D( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, mPPTBFTexture, 0 ); //glDrawBuffer(GL_COLOR_ATTACHMENT0); GLenum DrawBuffers[1] = { GL_COLOR_ATTACHMENT0 }; glDrawBuffers(1, DrawBuffers); GLenum fboStatus = glCheckFramebufferStatus( GL_FRAMEBUFFER ); // - check FBO status //GLenum fboStatus = glCheckNamedFramebufferStatus( mPPTBFFrameBuffer, GL_FRAMEBUFFER ); if ( fboStatus != GL_FRAMEBUFFER_COMPLETE ) { std::cout << "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" << std::endl; std::cout << "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" << std::endl; std::cout << "Framebuffer error - status: " << fboStatus << std::endl; std::cout << "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" << std::endl; std::cout << "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" << std::endl; // - clean device resources finalize(); // // - reset device state // glBindFramebuffer( GL_FRAMEBUFFER, 0 ); //return -1; } // - reset device state glBindFramebuffer( GL_FRAMEBUFFER, 0 ); glBindTexture( GL_TEXTURE_2D, 0 ); } /****************************************************************************** * Initialize shader program ******************************************************************************/ bool PtGraphicsHistogram::initializeShaderProgram() { bool statusOK = false; // Global variables const std::string shaderPath = PtEnvironment::mShaderPath + std::string( "/" ); PtShaderProgram* shaderProgram = nullptr; PtShaderProgram::TShaderList shaders; std::string shaderFilename; std::vector< std::string > uniforms; // [1] - Initialize shader program shaderProgram = mShaderProgram; shaderProgram->finalize(); shaderProgram->initialize(); shaderProgram->setName( "histogram" ); shaderProgram->setInfo( "Histogram" ); // - path shaders.clear(); shaderFilename = shaderPath + "histogram_vert.glsl"; shaders.push_back( std::make_pair( PtShaderProgram::ShaderType::eVertexShader, shaderFilename ) ); shaderFilename = shaderPath + "histogram_frag.glsl"; shaders.push_back( std::make_pair( PtShaderProgram::ShaderType::eFragmentShader, shaderFilename ) ); statusOK = shaderProgram->initializeProgram( shaders ); // Store uniforms info (after shader program link() step) uniforms.clear(); uniforms.push_back( "uTexture" ); uniforms.push_back( "uTextureWidth" ); // uniforms.push_back( "uNbBins" ); shaderProgram->registerUniforms( uniforms ); // Set uniform(s) that will never be modified (if no other shader link!) shaderProgram->use(); shaderProgram->set( 0, "uTexture" ); PtShaderProgram::unuse(); return statusOK; } /****************************************************************************** * Finalize ******************************************************************************/ void PtGraphicsHistogram::finalize() { if ( mPPTBFFrameBuffer ) { glDeleteFramebuffers( 1, &mPPTBFFrameBuffer ); mPPTBFFrameBuffer = 0; } if ( mPPTBFTexture ) { glDeleteTextures( 1, &mPPTBFTexture ); mPPTBFTexture = 0; } mShaderProgram->finalize(); } /****************************************************************************** * Get number of bins ******************************************************************************/ int PtGraphicsHistogram::getNbBins() const { return mNbBins; } /****************************************************************************** * Set number of bins ******************************************************************************/ void PtGraphicsHistogram::setNbBins( const int pValue ) { mNbBins = pValue; // Initialize framebuffer if ( mPPTBFFrameBuffer ) { glDeleteFramebuffers( 1, &mPPTBFFrameBuffer ); mPPTBFFrameBuffer = 0; } if ( mPPTBFTexture ) { glDeleteTextures( 1, &mPPTBFTexture ); mPPTBFTexture = 0; } initializeFramebuffer(); } /****************************************************************************** * Compute histogram on device (i.e. GPU) ******************************************************************************/ void PtGraphicsHistogram::compute( const GLuint pTexture, const int pTextureWidth, const int pTextureHeight ) { printf( "\nhistogram: %d x %d", pTextureWidth, pTextureHeight ); // Backup GL state GLint last_viewport[ 4 ]; glGetIntegerv( GL_VIEWPORT, last_viewport ); // Set and clear dedicated framebuffer //glBindFramebuffer( GL_DRAW_FRAMEBUFFER, mPPTBFFrameBuffer ); glBindFramebuffer( GL_FRAMEBUFFER, mPPTBFFrameBuffer ); // read-write glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, mPPTBFTexture); //glDrawBuffer( GL_COLOR_ATTACHMENT0 ); //glDrawBuffers(GL_COLOR_ATTACHMENT0); GLenum DrawBuffers[1] = { GL_COLOR_ATTACHMENT0 }; glDrawBuffers(1, DrawBuffers); //glReadBuffer( GL_COLOR_ATTACHMENT0 ); glClearColor( 0.f, 0.f, 0.f, 0.f ); glClear( GL_COLOR_BUFFER_BIT ); // Set viewport according to histogram size (1D + 1 fragment per bin) glViewport( 0, 0, mNbBins, 1 ); // Set GL state to manage histograms // - sum fragments value per bin glEnable( GL_BLEND ); glBlendFunc( GL_ONE, GL_ONE ); glBlendEquation( GL_FUNC_ADD ); glDisable( GL_DEPTH_TEST ); /*glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, mPPTBFTexture);*/ // Set texture(s) glBindTextureUnit( 0/*unit*/, pTexture ); // Set shader mShaderProgram->use(); // Set uniform(s) // mShaderProgram->set( 0, "uTexture" ); // mShaderProgram->set( pTextureWidth, "uTextureWidth" ); //mShaderProgram->set(mNbBins, "uNbBins"); //////------------------------------------------------------------------------------------ //std::vector< float > pHistogram; //pHistogram.resize(mNbBins, 0.f); //glReadPixels(0, 0, mNbBins/*width*/, 1/*height*/, GL_RED, GL_FLOAT, pHistogram.data()); //std::cout << "----------------------------------" << std::endl; //std::cout << "- HISTOGRAM" << std::endl; //for (const auto v : pHistogram) //{ // //std::cout << ( v / static_cast< float >( nbPixels ) ) << " "; // std::cout << v << " "; //} //std::cout << std::endl; //////------------------------------------------------------------------------------------ // Draw command(s) // - send points (as much image pixels) const int nbPixels = pTextureWidth * pTextureHeight; printf("\nnb pixels: %d", nbPixels ); glDrawArrays( GL_POINTS, 0, nbPixels ); // Reset shader PtShaderProgram::unuse(); // Restore modified GL state //glBindFramebuffer( GL_DRAW_FRAMEBUFFER, 0 ); glBindFramebuffer(GL_FRAMEBUFFER, 0); glDisable( GL_BLEND ); glEnable( GL_DEPTH_TEST ); glViewport( last_viewport[ 0 ], last_viewport[ 1 ], static_cast< GLsizei >( last_viewport[ 2 ] ), static_cast< GLsizei >( last_viewport[ 3 ] ) ); glClearColor( 0.45f, 0.55f, 0.60f, 1.00f ); //////------------------------------------------------------------------------------------ //std::vector< float > shaderData(mNbBins); //glGetTextureImage(mPPTBFTexture, 0/*level*/, GL_RED, GL_FLOAT, sizeof(float) * mNbBins, shaderData.data()); //auto result = std::minmax_element(shaderData.begin(), shaderData.end()); //std::cout << "\nhistogram: " << "(" << *(result.first) << "," << *(result.second) << ")" << std::endl; ////getchar(); ////------------------------------------------------------------------------------------ ////------------------------------------------------------------------------------------ //glBindFramebuffer(GL_READ_FRAMEBUFFER, mPPTBFFrameBuffer); //glReadBuffer(GL_COLOR_ATTACHMENT0); //// Retrieve histogram //pHistogram.resize(mNbBins, 0.f); //glReadPixels(0, 0, mNbBins/*width*/, 1/*height*/, GL_RED, GL_FLOAT, pHistogram.data()); //// Reset GL state(s) //glBindFramebuffer(GL_READ_FRAMEBUFFER, 0); ////------------------------------------------------------------------------------------ } /****************************************************************************** * Render ******************************************************************************/ void PtGraphicsHistogram::render() { } /****************************************************************************** * Retrieve histogram on host (i.e. CPU) ******************************************************************************/ void PtGraphicsHistogram::getHistogram( std::vector< float >& pHistogram, std::vector< float >& pCDF, const int pTextureWidth, const int pTextureHeight ) { // Configure GL state(s) //glNamedFramebufferReadBuffer( mPPTBFFrameBuffer, GL_COLOR_ATTACHMENT0 ); //glBindFramebuffer( GL_READ_FRAMEBUFFER, mPPTBFFrameBuffer ); glBindFramebuffer(GL_FRAMEBUFFER, mPPTBFFrameBuffer); glReadBuffer( GL_COLOR_ATTACHMENT0 ); //// - deal with odd texture dimensions //glBindTexture( GL_TEXTURE_2D, mPPTBFTexture ); //glPixelStorei( GL_PACK_ALIGNMENT, 1 ); //glPixelStorei( GL_PACK_ROW_LENGTH, 0 ); //glPixelStorei( GL_PACK_SKIP_PIXELS, 0 ); //glPixelStorei( GL_PACK_SKIP_ROWS, 0 ); // Retrieve histogram pHistogram.resize( mNbBins, 0.f ); //pHistogram.resize( 4 * mNbBins, 0.f ); glReadPixels( 0, 0, mNbBins/*width*/, 1/*height*/, GL_RED, GL_FLOAT, pHistogram.data() ); //glReadPixels( 0, 0, mNbBins/*width*/, 1/*height*/, GL_RGBA, GL_FLOAT, pHistogram.data() ); // Reset GL state(s) //glReadBuffer( GL_BACK ); // GL_FRONT //glBindFramebuffer( GL_READ_FRAMEBUFFER, 0 ); glBindFramebuffer(GL_FRAMEBUFFER, 0); //glBindFramebuffer( GL_FRAMEBUFFER, 0 ); // Build CDF (cumulative distribution function) pCDF.resize( mNbBins, 0.f ); //pCDF.resize( 4 * mNbBins, 0.f ); std::partial_sum( pHistogram.begin(), pHistogram.begin() + mNbBins, pCDF.begin() ); // DEBUG #if _DEBUG const int nbPixels = pTextureWidth * pTextureHeight; printf("\nnb pixels: %d", nbPixels); std::cout << "----------------------------------"<< std::endl; std::cout << "- HISTOGRAM" << std::endl; for ( const auto v : pHistogram ) { //std::cout << ( v / static_cast< float >( nbPixels ) ) << " "; std::cout << v << " "; } std::cout << std::endl; std::cout << "- CDF" << std::endl; for ( const auto v : pCDF ) { std::cout << ( v / static_cast< float >( nbPixels ) ) << " "; //std::cout << v << " "; } std::cout << std::endl; #endif }
14,678
C++
.cpp
349
39.928367
153
0.541245
ASTex-ICube/semiproctex
39
8
2
LGPL-2.1
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,924
SptHviewInterface.h
ASTex-ICube_semiproctex/Semiproc_synthesis_Src/SptSynthesizer/SptHviewInterface.h
/* * Publication: Semi-Procedural Textures Using Point Process Texture Basis Functions * Computer Graphics Forum (EGSR 2020 special issue) * Authors: P. Guehl , R. AllEgre , J.-M. Dischler, B. Benes , and E. Galin * * Code author: Pascal Guehl */ /** * @version 1.0 */ #ifndef _SPT_HVIEW_INTERFACE_H_ #define _SPT_HVIEW_INTERFACE_H_ /****************************************************************************** ******************************* INCLUDE SECTION ****************************** ******************************************************************************/ #ifndef M_PI #define M_PI 3.14159265358979323846 #endif // hview #include <hvVec2.h> #include <hvArray2.h> #include <hvBitmap.h> #include <hvPictRGB.h> // STL #include <string> /****************************************************************************** ************************* DEFINE AND CONSTANT SECTION ************************ ******************************************************************************/ /****************************************************************************** ***************************** TYPE DEFINITION ******************************** ******************************************************************************/ /****************************************************************************** ******************************** CLASS USED ********************************** ******************************************************************************/ /****************************************************************************** ****************************** CLASS DEFINITION ****************************** ******************************************************************************/ namespace Spt { /** * @class SptHviewInterface * * @brief The SptHviewInterface class provides interface to the hview software texture synthesis api. * * SptHviewInterface is an wrapper interaface the hview software texture synthesis api. */ class SptHviewInterface { /************************************************************************** ***************************** PUBLIC SECTION ***************************** **************************************************************************/ public: /******************************* INNER TYPES *******************************/ /******************************* ATTRIBUTES *******************************/ /******************************** METHODS *********************************/ /** * Constructor */ SptHviewInterface(); /** * Destructor */ virtual ~SptHviewInterface(); /** * Initialize */ void initialize(); /** * Finalize */ void finalize(); /** * Launch the synthesis pipeline */ void execute(); /** * Load exemplar (color texture) * * @param pFilename */ void loadExemplar( const char* pFilename ); /** * Load structure map (binary) * * @param pFilename */ void loadExemplarStructureMap( const char* pFilename ); /** * Load distance map * * @param pFilename */ void loadExemplarDistanceMap( const char* pFilename ); /** * Load label map * * @param pFilename */ void loadExemplarLabelMap( const char* pFilename ); /** * Load guidance PPTBF * * @param pFilename */ void loadGuidancePPTBF( const char* pFilename ); /** * Load guidance mask * * @param pFilename */ void loadGuidanceMask( const char* pFilename ); /** * Load guidance distance map * * @param pFilename */ void loadGuidanceDistanceMap( const char* pFilename ); /** * Load guidance label map * * @param pFilename */ void loadGuidanceLabelMap( const char* pFilename ); /************************************************************************** **************************** PROTECTED SECTION *************************** **************************************************************************/ protected: /******************************* INNER TYPES *******************************/ /******************************* ATTRIBUTES *******************************/ /** * hview synthesis parameters */ // - input exemplar name std::string mName; // - synthesis algorithm int mSTOPATLEVEL; // - global translation (used for large maps generated in smaller tiles) int mPosx; int mPosy; // - exemplar hview::hvPictRGB< unsigned char > mExample; // - exemplar distance map hview::hvPictRGB<unsigned char> mExdist; double mWeight; // weight color vs distance // - synthesis algorithm double mPowr; // ... float mIndweight; // amount of error added when error on labels while searching for better pixel candidates int mNeighbor; // neighborhood half-patch size while searching for better pixel candidates int mAtlevel; // starting level of the pyramid LOD hierarchy int mBsize; // block size at starting level float mERR; // error at smart initialization // - guidance mask (thresholded PPTBF + potential constraints relaxation on structure borders) hview::hvBitmap mMask; // - guidance distance and labels hview::hvPictRGB<unsigned char> mGuidance; // - main synthesized UV map (indirection map: texture coordinates) hview::hvArray2< hview::hvVec2< int > > mIndex; // - synthesized output texture hview::hvPictRGB< unsigned char > mRes; /******************************** METHODS *********************************/ /************************************************************************** ***************************** PRIVATE SECTION **************************** **************************************************************************/ private: /******************************* INNER TYPES *******************************/ /******************************* ATTRIBUTES *******************************/ /******************************** METHODS *********************************/ }; // end of class SptHviewInterface } // end of namespace Spt /****************************************************************************** ******************************* INLINE SECTION ****************************** ******************************************************************************/ #endif // _SPT_HVIEW_INTERFACE_H_
6,198
C++
.h
173
33.398844
108
0.418632
ASTex-ICube/semiproctex
39
8
2
LGPL-2.1
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,925
SptBasicSynthesizer.h
ASTex-ICube_semiproctex/Semiproc_synthesis_Src/SptSynthesizer/SptBasicSynthesizer.h
/* * Publication: Semi-Procedural Textures Using Point Process Texture Basis Functions * Computer Graphics Forum (EGSR 2020 special issue) * Authors: P. Guehl , R. AllEgre , J.-M. Dischler, B. Benes , and E. Galin * * Code author: Pascal Guehl */ /** * @version 1.0 */ #ifndef _SPT_BASIC_SYNTHESIZER_H_ #define _SPT_BASIC_SYNTHESIZER_H_ /****************************************************************************** ******************************* INCLUDE SECTION ****************************** ******************************************************************************/ // STL #include <string> /****************************************************************************** ************************* DEFINE AND CONSTANT SECTION ************************ ******************************************************************************/ /****************************************************************************** ***************************** TYPE DEFINITION ******************************** ******************************************************************************/ /****************************************************************************** ******************************** CLASS USED ********************************** ******************************************************************************/ // Project namespace Spt { class SptBasicHviewInterface; } /****************************************************************************** ****************************** CLASS DEFINITION ****************************** ******************************************************************************/ namespace Spt { /** * @class SptBasicSynthesizer * * @brief The SptBasicSynthesizer class provides interface to semi-procedural texture synthesis model. * * Semi-procedural texture synthesis separate process in two: * procedural stochastic structures are synthesized procedurally, * then color details are transfer through data-driven by-example synthesis. * * SptBasicSynthesizer is a basic synthesizer that only requires 3 files: * - an input exemplar name xxx_scrop.png * - an input segmented exemplar name xxx_seg_scrop.png * - a pptbf parameters file xxx_seg_scrop_pptbf_params.txt * where xxx is texture name. * * Launch command: SptBasicSynthesizer.exe cracked_asphalt_160796 0.9 0.5 2 64 100 0.0 * * Detailed parameters : TODO => detail parameters list! * Example : * GUIDE 0.9 * STRENGTH 0.5 * INITLEVEL 2 * BLOCSIZE 64 * INITERR 100 * INDEXWEIGHT 0 */ class SptBasicSynthesizer { /************************************************************************** ***************************** PUBLIC SECTION ***************************** **************************************************************************/ public: /******************************* INNER TYPES *******************************/ /******************************* ATTRIBUTES *******************************/ /******************************** METHODS *********************************/ /** * Constructor */ SptBasicSynthesizer(); /** * Destructor */ virtual ~SptBasicSynthesizer(); /** * Initialize */ void initialize(); /** * Finalize */ void finalize(); /** * Launch the synthesis pipeline */ virtual void execute(); /** * Save/export synthesis results */ virtual void saveResults(); /** * Semi-procedural texture synthesis parameters */ void setExemplarName( const char* pText ); void setGUIDE( const float pValue ); void setSTRENGTH( const float pValue ); void setINITLEVEL( const int pValue ); void setBLOCSIZE( const int pValue ); void setINITERR( const float pValue ); void setINDEXWEIGHT( const float pValue ); /************************************************************************** **************************** PROTECTED SECTION *************************** **************************************************************************/ protected: /******************************* INNER TYPES *******************************/ /******************************* ATTRIBUTES *******************************/ /** * Interface to hview api */ SptBasicHviewInterface* mHviewInterface; ///** // * Semi-procedural texture synthesis parameters // */ //float GUIDE; //float STRENGTH; //int INITLEVEL; //int BLOCSIZE; //float INITERR; //float INDEXWEIGHT; /******************************** METHODS *********************************/ /************************************************************************** ***************************** PRIVATE SECTION **************************** **************************************************************************/ private: /******************************* INNER TYPES *******************************/ /******************************* ATTRIBUTES *******************************/ /******************************** METHODS *********************************/ }; // end of class SptBasicSynthesizer } // end of namespace Spt /****************************************************************************** ******************************* INLINE SECTION ****************************** ******************************************************************************/ #endif // _SPT_BASIC_SYNTHESIZER_H_
5,336
C++
.h
138
36.210145
103
0.372625
ASTex-ICube/semiproctex
39
8
2
LGPL-2.1
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,926
SptBasicHviewInterface.h
ASTex-ICube_semiproctex/Semiproc_synthesis_Src/SptSynthesizer/SptBasicHviewInterface.h
/* * Publication: Semi-Procedural Textures Using Point Process Texture Basis Functions * Computer Graphics Forum (EGSR 2020 special issue) * Authors: P. Guehl , R. AllEgre , J.-M. Dischler, B. Benes , and E. Galin * * Code author: Pascal Guehl */ /** * @version 1.0 */ #ifndef _SPT_BASIC_HVIEW_INTERFACE_H_ #define _SPT_BASIC_HVIEW_INTERFACE_H_ /****************************************************************************** ******************************* INCLUDE SECTION ****************************** ******************************************************************************/ // STL #include <string> /****************************************************************************** ************************* DEFINE AND CONSTANT SECTION ************************ ******************************************************************************/ /****************************************************************************** ***************************** TYPE DEFINITION ******************************** ******************************************************************************/ /****************************************************************************** ******************************** CLASS USED ********************************** ******************************************************************************/ namespace hview { template< class T > class hvPict; } /****************************************************************************** ****************************** CLASS DEFINITION ****************************** ******************************************************************************/ namespace Spt { /** * @class SptBasicHviewInterface * * @brief The SptBasicHviewInterface class provides interface to the hview software texture synthesis api. * * SptBasicHviewInterface is an wrapper interaface the hview software texture synthesis api. */ class SptBasicHviewInterface { /************************************************************************** ***************************** PUBLIC SECTION ***************************** **************************************************************************/ public: /******************************* INNER TYPES *******************************/ /******************************* ATTRIBUTES *******************************/ /******************************** METHODS *********************************/ /** * Constructor */ SptBasicHviewInterface(); /** * Destructor */ virtual ~SptBasicHviewInterface(); /** * Initialize */ void initialize(); /** * Finalize */ void finalize(); /** * Launch the synthesis pipeline */ void execute(); /** * Semi-procedural texture synthesis parameters */ void setExemplarName( const char* pText ); void setGUIDE( const float pValue ); void setSTRENGTH( const float pValue ); void setINITLEVEL( const int pValue ); void setBLOCSIZE( const int pValue ); void setINITERR( const float pValue ); void setINDEXWEIGHT( const float pValue ); /************************************************************************** **************************** PROTECTED SECTION *************************** **************************************************************************/ protected: /******************************* INNER TYPES *******************************/ /******************************* ATTRIBUTES *******************************/ /** * Semi-procedural texture synthesis parameters */ std::string mExemplarName; float GUIDE; float STRENGTH; int INITLEVEL; int BLOCSIZE; float INITERR; float INDEXWEIGHT; int padding; /******************************** METHODS *********************************/ void pptbfshader( float pixelzoom, hview::hvPict< float >& pptbfpi, hview::hvPict< float >& ppval ); /************************************************************************** ***************************** PRIVATE SECTION **************************** **************************************************************************/ private: /******************************* INNER TYPES *******************************/ /******************************* ATTRIBUTES *******************************/ /******************************** METHODS *********************************/ }; // end of class SptBasicHviewInterface } // end of namespace Spt /****************************************************************************** ******************************* INLINE SECTION ****************************** ******************************************************************************/ #endif // _SPT_BASIC_HVIEW_INTERFACE_H_
4,682
C++
.h
114
38.666667
107
0.325525
ASTex-ICube/semiproctex
39
8
2
LGPL-2.1
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,927
SptImageHelper.h
ASTex-ICube_semiproctex/Semiproc_synthesis_Src/SptSynthesizer/SptImageHelper.h
/* * Publication: Semi-Procedural Textures Using Point Process Texture Basis Functions * Computer Graphics Forum (EGSR 2020 special issue) * Authors: P. Guehl , R. AllEgre , J.-M. Dischler, B. Benes , and E. Galin * * Code author: Pascal Guehl */ /** * @version 1.0 */ #ifndef _SPT_IMAGE_HELPER_H_ #define _SPT_IMAGE_HELPER_H_ /****************************************************************************** ******************************* INCLUDE SECTION ****************************** ******************************************************************************/ /****************************************************************************** ************************* DEFINE AND CONSTANT SECTION ************************ ******************************************************************************/ /****************************************************************************** ***************************** TYPE DEFINITION ******************************** ******************************************************************************/ /****************************************************************************** ******************************** CLASS USED ********************************** ******************************************************************************/ /****************************************************************************** ****************************** CLASS DEFINITION ****************************** ******************************************************************************/ namespace Spt { /** * @class SptImageHelper * * @brief The SptImageHelper class provides interface to the stb image management library. */ class SptImageHelper { /************************************************************************** ***************************** PUBLIC SECTION ***************************** **************************************************************************/ public: /******************************* INNER TYPES *******************************/ /******************************* ATTRIBUTES *******************************/ /******************************** METHODS *********************************/ /** * Load image */ static void loadImage( const char* pFilename, int& pWidth, int& pHeight, int& pNrChannels, unsigned char*& pData, int desired_channels = 0 ); /** * Save image */ static int saveImage( const char* pFilename, const int pWidth, const int pHeight, const int pNrChannels, const void* pData ); /** * Free image data */ static void freeImage( unsigned char* pData ); /************************************************************************** **************************** PROTECTED SECTION *************************** **************************************************************************/ protected: /******************************* INNER TYPES *******************************/ /******************************* ATTRIBUTES *******************************/ /******************************** METHODS *********************************/ /************************************************************************** ***************************** PRIVATE SECTION **************************** **************************************************************************/ private: /******************************* INNER TYPES *******************************/ /******************************* ATTRIBUTES *******************************/ /******************************** METHODS *********************************/ }; // end of class SptImageHelper } // end of namespace Spt /****************************************************************************** ******************************* INLINE SECTION ****************************** ******************************************************************************/ #endif // _SPT_IMAGE_HELPER_H_
3,921
C++
.h
75
49.813333
142
0.241669
ASTex-ICube/semiproctex
39
8
2
LGPL-2.1
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,928
SptSynthesizer.h
ASTex-ICube_semiproctex/Semiproc_synthesis_Src/SptSynthesizer/SptSynthesizer.h
/* * Publication: Semi-Procedural Textures Using Point Process Texture Basis Functions * Computer Graphics Forum (EGSR 2020 special issue) * Authors: P. Guehl , R. AllEgre , J.-M. Dischler, B. Benes , and E. Galin * * Code author: Pascal Guehl */ /** * @version 1.0 */ #ifndef _SPT_SYNTHESIZER_H_ #define _SPT_SYNTHESIZER_H_ /****************************************************************************** ******************************* INCLUDE SECTION ****************************** ******************************************************************************/ // STL #include <string> /****************************************************************************** ************************* DEFINE AND CONSTANT SECTION ************************ ******************************************************************************/ /****************************************************************************** ***************************** TYPE DEFINITION ******************************** ******************************************************************************/ /****************************************************************************** ******************************** CLASS USED ********************************** ******************************************************************************/ // Project namespace Spt { class SptHviewInterface; } /****************************************************************************** ****************************** CLASS DEFINITION ****************************** ******************************************************************************/ namespace Spt { /** * @class SptSynthesizer * * @brief The SptSynthesizer class provides interface to semi-procedural texture synthesis model. * * Semi-procedural texture synthesis separate process in two: * procedural stochastic structures are synthesized procedurally, * then color details are transfer through data-driven by-example synthesis. * * Example of parameter file: * * [EXEMPLAR] * name TexturesCom_Crackles0011_S * exemplarSize 512 512 * [SYNTHESIS] * outputSize 1024 1024 * [PYRAMID] * nbMipmapLevels 10 * pyramidMaxLevel 9 * pyramidMinSize 32 * nbPyramidLevels 5 * [BLOCK INITIALIZATION] * blockGrid 8 8 * blockSize 128 128 * useSmartInitialization 0 * smartInitNbPasses 10 * [CORRECTION PASS] * correctionNbPasses 3 * correctionSubPassBlockSize 3 * correctionNeighborhoodSize 2 * correctionNeighborSearchRadius 4 * correctionNeighborSearchNbSamples 11 * correctionNeighborSearchDDepth 3 * [MATERIAL] * correctionWeightAlbedo 1 * correctionWeightHeight 1 * correctionWeightNormal 1 * correctionWeightRoughness 1 * [LABEL MAP] * useLabelMap 1 * labelmapType 0 * useLabelSampler 0 * labelSamplerAreaThreshold 2500 * [GUIDANCE] * correctionGuidanceWeight 0.85 * correctionExemplarWeightDistance 0 * correctionGuidanceWeightDistance 0 * correctionLabelErrorAmount 0.25 * [SEMI PROCEDURAL] * PPTBFThreshold 0.109375 * relaxContraints 0.09375 0.210938 * guidanceWeight 0.763 0 * distancePower 0.1 * initializationError 0.196078 * nbLabels 6 * [PPTBF] * shift 10 10 * */ class SptSynthesizer { /************************************************************************** ***************************** PUBLIC SECTION ***************************** **************************************************************************/ public: /******************************* INNER TYPES *******************************/ /******************************* ATTRIBUTES *******************************/ /******************************** METHODS *********************************/ /** * Constructor */ SptSynthesizer(); /** * Destructor */ virtual ~SptSynthesizer(); /** * Initialize */ void initialize(); /** * Finalize */ void finalize(); /** * Load synthesis parameters * * @param pFilename * * @return error status */ int loadParameters( const char* pFilename ); /** * Launch the synthesis pipeline */ virtual void execute(); /** * Save/export synthesis results */ virtual void saveResults(); /************************************************************************** **************************** PROTECTED SECTION *************************** **************************************************************************/ protected: /******************************* INNER TYPES *******************************/ /******************************* ATTRIBUTES *******************************/ /** * Interface to hview api */ SptHviewInterface* mHviewInterface; /** * Semi-procedural texture synthesis parameters */ // - exemplar std::string mExemplarName; int mExemplarWidth; int mExemplarHeight; // - output int mOutputWidth; int mOutputHeight; // - pyramid int mPyramidNbMipmapLevels; int mPyramidMaxLevel; int mPyramidMinSize; int mPyramidNbLevels; // - block initialization int mblockInitGridWidth; int mblockInitGridHeight; int mblockInitBlockWidth; int mblockInitBlockHeight; bool mblockInitUseSmartInitialization; int mblockInitSmartInitNbPasses; // - correction pass int mCorrectionNbPasses; int mCorrectionSubPassBlockSize; int mCorrectionNeighborhoodSize; int mCorrectionNeighborSearchRadius; int mCorrectionNeighborSearchNbSamples; int mCorrectionNeighborSearchDepth; // - material float mCorrectionWeightAlbedo; float mCorrectionWeightHeight; float mCorrectionWeightNormal; float mCorrectionWeightRoughness; // - label map bool mUseLabelMap; int mLabelmapType; bool mUseLabelSampler; float mLabelSamplerAreaThreshold; // - guidance float mCorrectionGuidanceWeight; float mCorrectionExemplarWeightDistance; float mCorrectionGuidanceWeightDistance; float mCorrectionLabelErrorAmount; // - semi-procedural float mSemiProcTexPPTBFThreshold; float mSemiProcTexRelaxContraintMin; float mSemiProcTexRelaxContraintMax; float mSemiProcTexGuidanceWeight; float mSemiProcTexDistancePower; float mSemiProcTexInitializationError; int mSemiProcTexNbLabels; // - PPTBF int mPptbfShiftX; int mPptbfShiftY; /******************************** METHODS *********************************/ /** * Initialization stage * - strategies/policies to choose blocks at initialization */ virtual void smartInitialization(); /** * Correction pass */ virtual void correction(); /** * Upsampling pass */ virtual void upsampling(); /** * Load exemplar (color texture) * * @param pFilename */ void loadExemplar( const char* pFilename ); /** * Load structure map (binary) * * @param pFilename */ void loadExemplarStructureMap( const char* pFilename ); /** * Load distance map * * @param pFilename */ void loadExemplarDistanceMap( const char* pFilename ); /** * Load label map * * @param pFilename */ void loadExemplarLabelMap( const char* pFilename ); /** * Load guidance PPTBF * * @param pFilename */ void loadGuidancePPTBF( const char* pFilename ); /** * Load guidance mask * * @param pFilename */ void loadGuidanceMask( const char* pFilename ); /** * Load guidance distance map * * @param pFilename */ void loadGuidanceDistanceMap( const char* pFilename ); /** * Load guidance label map * * @param pFilename */ void loadGuidanceLabelMap( const char* pFilename ); /************************************************************************** ***************************** PRIVATE SECTION **************************** **************************************************************************/ private: /******************************* INNER TYPES *******************************/ /******************************* ATTRIBUTES *******************************/ /******************************** METHODS *********************************/ }; // end of class SptSynthesizer } // end of namespace Spt /****************************************************************************** ******************************* INLINE SECTION ****************************** ******************************************************************************/ #endif // _SPT_SYNTHESIZER_H_
8,308
C++
.h
276
27.550725
98
0.514973
ASTex-ICube/semiproctex
39
8
2
LGPL-2.1
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,929
hviTransform.h
ASTex-ICube_semiproctex/Semiproc_synthesis_Src/3rdParty/Externals/hview/hviTransform.h
/* * Code author: Jean-Michel Dischler */ /** * @version 1.0 */ // hviTransform.h: interface (abstract object) for a Transformation. // // JMD 1/01/2007 ////////////////////////////////////////////////////////////////////// #if !defined(AFX_TRANSFORM_H__B6AC0A32_75EF_428E_BC10_6219F619FA29__INCLUDED_) #define AFX_TRANSFORM_H__B6AC0A32_75EF_428E_BC10_6219F619FA29__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 //////////////////////////////////////////// /* A Transformation T consists of a conversion of an object U to another object of the same data type U The interface implements following issues: the application of the transform to an object U and the composition of two transforms Neutral transform is called Identity. */ //////////////////////////////////////////// //////////////////////////////////////////// namespace hview { template <class T, class U> class hviTransform { public: // apply a transform to an object of type T, returns another object of type T virtual U apply(const U &a) const =0; // compose two transforms virtual void compose(const T &a, const T &b) =0; // set identity virtual void setIdentity() =0; }; } #endif // !defined(AFX_ALGEBRA_H__B6AC0A32_75EF_428E_BC10_6219F619FA29__INCLUDED_)
1,270
C++
.h
38
31.789474
100
0.631751
ASTex-ICube/semiproctex
39
8
2
LGPL-2.1
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,930
hvError.h
ASTex-ICube_semiproctex/Semiproc_synthesis_Src/3rdParty/Externals/hview/hvError.h
/* * Code author: Jean-Michel Dischler */ /** * @version 1.0 */ #if !defined(AFX_ERROR_H__09002DDD_2472_43B9_B7B6_FCB6FF1B6B0D__INCLUDED_) #define AFX_ERROR_H__09002DDD_2472_43B9_B7B6_FCB6FF1B6B0D__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include <iostream> #include <cstdlib> inline void hvFatal(const char *str) { std::cout<<"Internal error:"<<str<<"\n"; char buffer[16]; std::cin.getline(buffer,16); abort(); } #endif // !defined(AFX_ARRAY1_H__09002DDD_2472_43B9_B7B6_FCB6FF1B6B0D__INCLUDED_)
540
C++
.h
21
24
81
0.720703
ASTex-ICube/semiproctex
39
8
2
LGPL-2.1
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,931
hvVec2.h
ASTex-ICube_semiproctex/Semiproc_synthesis_Src/3rdParty/Externals/hview/hvVec2.h
/* * Code author: Jean-Michel Dischler */ /** * @version 1.0 */ // hvVec2.h: interface for the vec2 class. // // defines a vector in 2D // By JMD 8/8/04 ////////////////////////////////////////////////////////////////////// #if !defined(AFX_VEC2_H__954C4849_5D4B_4173_9842_797C84C6FB1B__INCLUDED_) #define AFX_VEC2_H__954C4849_5D4B_4173_9842_797C84C6FB1B__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include <math.h> #include "hvError.h" namespace hview { template <class T> class hvVec2 { protected: T x, y; public: //////// constructors hvVec2<T>():x(T(0)),y(T(0)) { } hvVec2<T>(T a):x(a),y(a) { } hvVec2<T>(T a, T b):x(a),y(b) { } template <class X> void cast(const hvVec2<X> &v) { x=T(v.X()); y=T(v.Y()); } // define vector from two points (a,b): v=ab void PVec(const hvVec2<T> &a, const hvVec2<T> &b) { x=b.x-a.x; y=b.y-a.y; } //////// selectors for coordinates T X() const { return x; } T Y() const { return y; } T &operator[](int i) { if (i!=0 && i!=1) { hvFatal("out of vec2 range!"); } if (i==0) return x; return y; } /////// operations: addition, substraction, multiplication and division void add(const hvVec2<T> &a, const hvVec2<T> &b) { x=a.x+b.x; y=a.y+b.y; } hvVec2 operator+(const hvVec2<T> &b) const { hvVec2<T> vv; vv.x=x+b.x; vv.y=y+b.y; return vv;} void operator+=(const hvVec2<T> &b) { x+=b.x; y+=b.y; } void sub(const hvVec2<T> &a, const hvVec2<T> &b) { x=a.x-b.x; y=a.y-b.y; } hvVec2 operator-(const hvVec2<T> &b) const { hvVec2<T> vv; vv.x=x-b.x; vv.y=y-b.y; return vv;} void operator-=(const hvVec2<T> &b) { x-=b.x; y-=b.y; } void mult(const hvVec2<T> &a, const hvVec2<T> &b) { x=b.x*a.x; y=b.y*a.y; } hvVec2<T> operator*(const hvVec2<T> &b) const { hvVec2<T> vv; vv.x=x*b.x; vv.y=y*b.y; return vv;} void operator*=(const hvVec2<T> &b) { x*=b.x; y*=b.y; } void operator*=(T v) { x*=v; y*=v; } template <class X> void operator*=(X v) { x= (T)((X)x*v); y=(T)((X)y*v); } void div(const hvVec2<T> &a, const hvVec2<T> &b) { x=a.x/b.x; y=a.y/b.y; } hvVec2<T> operator/(const hvVec2<T> &b) const { hvVec2<T> vv; vv.x=x/b.x; vv.y=y/b.y; return vv;} void operator/=(const hvVec2<T> &b) { x/=b.x; y/=b.y; } void operator/=(T v) { x/=v; y/=v; } template <class X> void operator/=(X v) { x= (T)((X)x/v); y=(T)((X)y/v); } // scale by scalar value void scale(const hvVec2<T> &a, T k) { x=a.x*k; y=a.y*k; } void scale(T k) { x*=k; y*=k; } template <class X> void scale(X v) { x= (T)((X)x*v); y=(T)((X)y*v); } // divide by scalar, this scalar cannot be null void normalize(T norme) { x /= norme; y /= norme; } void divScale(T k) { x/=k; y/=k; } template <class X> void divScale(X v) { x= (T)((X)x/v); y=(T)((X)y/v); } // absolute value component by component void abs() { if (x<T(0)) x = -x; if (y<T(0)) y = -y; } // Trunc to max value void trunc(T max) { if (x>max) x = max; if (y>max) y = max; } // random vector void random() { x = ((T)((double)rand()/(double)RAND_MAX)); y = ((T)((double)rand()/(double)RAND_MAX)); } // points hvVec2<T> shift(const hvVec2<T> &p, const hvVec2<T> &dir, T length) { x = p.x+length*dir.x; y = p.y+length*dir.y; } void boxPoints(const hvVec2<T> &dir, T length, hvVec2<T> points[]) const { points[0]=*this; points[1]=hvVec2<T>(x, y+dir.y*length); points[2]=hvVec2<T>(x+dir.x*length, y); points[3]=hvVec2<T>(x+dir.x*length,y+dir.y*length); } // dot product (produit scalaire) T dot(const hvVec2<T> v) const { return x*v.x+y*v.y; } // opposite vector void reverse() { x=-x; y=-y; } hvVec2<T> operator-() { hvVec2<T> v(-x,-y); return v; } // cross product (determinant) T det( const hvVec2<T> &v2) const { return x*v2.y-y*v2.x; } // cross product (determinant) T cross( const hvVec2<T> &v2) const { return x*v2.y-y*v2.x; } // compute median vector between a and b, result is not normalized void bissec( const hvVec2<T> &a, const hvVec2<T> &b) { add(a,b); scale(0.5); } // linear interpolation between v1 and v2 //according to t (between 0 and 1), t must be a float or double //if t=0 result is v1, if t=1 result is v2 //result is not normalized template <class X> void interpolate(const hvVec2<T> &v1, const hvVec2<T> &v2, X t) { x = (T)(((X)1.0-t)*(X)v1.x + t*(X)v2.x); y = (T)(((X)1.0-t)*(X)v1.y + t*(X)v2.y); } // linear interpolation between v1 and v2 //according to vector t; each component of t is between 0 and 1 and gives coefficient, //result is not normalized template <class X> void interpolate(const hvVec2<T> &v1, const hvVec2<T> &v2, const hvVec2<X> &t) { x = (T)(((X)1.0-t.x)*(X)v1.x + t.x*(X)v2.x); y = (T)(((X)1.0-t.y)*(X)v1.y + t.y*(X)v2.y); } // compares component by component and keeps the min one // result is not normalized void keepMin(const hvVec2<T> &v1, const hvVec2<T> &v2) { if (v1.x<v2.x) x = v1.x; else x = v2.x; if (v1.y<v2.y) y = v1.y; else y = v2.y; } // compares component by component and keeps the max one // result is not normalized void keepMax(const hvVec2<T> &v1, const hvVec2<T> &v2) { if (v1.x>v2.x) x = v1.x; else x = v2.x; if (v1.y>v2.y) y = v1.y; else y = v2.y; } // returns the largest / smallest component T maxCoord() const { if (x>y) return x; return y; } T minCoord() const { if (x<y) return x; return y; } // returns the euclidian distance between two points T distance( const hvVec2<T> &a) const { hvVec2<T> r; r.PVec(a, *this); return r.norm(); } // compares two vectors bool equals(const hvVec2<T> &p1) const { return (p1.x==x) && (p1.y==y) ; } bool operator==(const hvVec2<T> &p1) const { return (p1.x==x) && (p1.y==y) ; } bool areClose(const hvVec2<T> &p1, T dist) const { hvVec2<T> v; v.PVec(p1, *this); v.abs(); if (v.x<dist && v.y<dist ) return true; return false; } // computes the norm (vector length) T normSquared() const { return x*x+y*y; } double normSquaredDouble() const { return (double)x*(double)x+(double)y*(double)y; } T norm() const { return (T) sqrt(normSquaredDouble()); } // compare to zero bool isNull() const { return x==T(0) && y==T(0) ; } // test if all components are small (lower than dist) bool isQNull(T dist) const { hvVec2<T> v=*this; v.abs(); return v.x<=dist && v.y<=dist ; } }; } #endif // !defined(AFX_VEC2_H__954C4849_5D4B_4173_9842_797C84C6FB1B__INCLUDED_)
6,445
C++
.h
201
29.462687
98
0.607131
ASTex-ICube/semiproctex
39
8
2
LGPL-2.1
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,932
hvPicture.h
ASTex-ICube_semiproctex/Semiproc_synthesis_Src/3rdParty/Externals/hview/hvPicture.h
/* * Code author: Jean-Michel Dischler */ /** * @version 1.0 */ // hvPicture.h: interface for the picture class. // ////////////////////////////////////////////////////////////////////// #if !defined(AFX_PICTURE_H__098453F0_1C38_49E9_A6F4_AABF90AA55E8__INCLUDED_) #define AFX_PICTURE_H__098453F0_1C38_49E9_A6F4_AABF90AA55E8__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include "hvBitmap.h" #include "hvPict.h" #include "hvPictRGB.h" namespace hview { //////////////////////////////////////////////////////////// // template <class T> class hvPict : public hvField2< T > template <class T> template <class X, class Y> hvPict<T>::hvPict(const hvPictRGB<X> &pict, Y scal, int x, int y, int sx, int sy) : hvField2< T >(sx - x + 1, sy - y + 1, T(0)), hvArray2< T >(sx - x + 1, sy - y + 1, T(0)) { this->reset(pict.sizeX(), pict.sizeY(), T(0)); int i, j; for (i = x; i <= sx; i++) for (j = y; j <= sy; j++) { this->update(i - x, j - y, T(Y((pict.get(i, j)).luminance())*scal)); } } template <class T> template <class X, class Y> void hvPict<T>::convert(const hvPictRGB<X> &pict, hvPictComponent cc, Y scal) { this->reset(pict.sizeX(), pict.sizeY(), T(0)); int i, j; for (i = 0; i<pict.sizeX(); i++) for (j = 0; j<pict.sizeY(); j++) { Y v; hvColRGB<X> co = pict.get(i, j); switch (cc) { case HV_RED: v = Y(co.RED()); break; case HV_GREEN: v = Y(co.GREEN()); break; case HV_BLUE: v = Y(co.BLUE()); break; default: v = Y(co.luminance()); } this->update(i, j, T(v*scal)); } } template <class T> template <class X, class Y> hvPict<T>::hvPict(const hvPictRGB<X> &pict, hvPictComponent cc, Y scal, int x, int y, int sx, int sy) : hvField2< T >(sx - x + 1, sy - y + 1, T(0)), hvArray2< T >(sx - x + 1, sy - y + 1, T(0)) { int i, j; for (i = x; i <= sx; i++) for (j = y; j <= sy; j++) { Y v; hvColRGB<X> co = pict.get(i, j); switch (cc) { case HV_RED: v = Y(co.RED()); break; case HV_GREEN: v = Y(co.GREEN()); break; case HV_BLUE: v = Y(co.BLUE()); break; default: v = Y(co.luminance()); } this->update(i - x, j - y, T(v*scal)); //printf("%d,%d=%d\n",i,j,get(i-x,j-y)); } } template <class T> template <class X, class Y> hvPict<T>::hvPict(const hvPictRGBA<X> &pict, Y scal, int x, int y, int sx, int sy) : hvField2< T >(sx - x + 1, sy - y + 1, T(0)), hvArray2< T >(sx - x + 1, sy - y + 1, T(0)) { int i, j; for (i = x; i <= this->sizeX(); i++) for (j = y; j <= this->sizeY(); j++) { this->update(i - x, j - y, T(Y((pict.get(i, j)).luminance())*scal)); } } template <class T> template <class X, class Y> hvPict<T>::hvPict(const hvPictRGBA<X> &pict, hvPictComponent cc, Y scal, int x, int y, int sx, int sy) : hvField2< T >(sx - x + 1, sy - y + 1, T(0)), hvArray2< T >(sx - x + 1, sy - y + 1, T(0)) { int i, j; for (i = x; i <= this->sizeX(); i++) for (j = y; j <= this->sizeY(); j++) { Y v; hvColRGBA<X> co = pict.get(i, j); switch (cc) { case HV_RED: v = Y(co.RED()); break; case HV_GREEN: v = Y(co.GREEN()); break; case HV_BLUE: v = Y(co.BLUE()); break; case HV_ALPHA: v = Y(co.ALPHA()); break; default: v = Y(co.luminance()); } this->update(i - x, j - y, T(v*scal)); } } template <class T> void hvPict<T>::squaredDifference(int px, int py, int dx, int dy, const hvPictRGB<unsigned char> &pia, int ix, int iy, const hvPictRGB<unsigned char> &pib) { int i, j; this->reset(dx, dy, T(0)); for (i = 0; i<dx; i++) for (j = 0; j<dy; j++) { int kx = px + i; while (kx<0) kx += pia.sizeX(); while (kx >= pia.sizeX()) kx -= pia.sizeX(); int ky = py + j; while (ky<0) ky += pia.sizeY(); while (ky >= pia.sizeY()) ky -= pia.sizeY(); this->update(i, j, T(pia.get(kx, ky).squaredDifference(pib.get(ix + i, iy + j)))); } } //////////////////////////////////////////////////////////// //template <class T> class hvPictRGB : public hvField2< hvColRGB<T> > template <class T> template <class U, class V> hvPictRGB<T>::hvPictRGB(const hvPict<U> &p, V scal) { int i, j; V val; hvArray2< hvColRGB<T> >::reset(p.sizeX(), p.sizeY(), hvColRGB<T>(0)); for (i = 0; i<p.sizeX(); i++) for (j = 0; j<p.sizeY(); j++) { val = V(p.get(i, j)); val *= scal; this->update(i, j, hvColRGB<T>(T(val), T(val), T(val))); } } template <class T> template <class U, class V> hvPictRGB<T>::hvPictRGB(const hvPict<U> &p, V scal, V shift) { int i, j; V val; hvArray2< hvColRGB<T> >::reset(p.sizeX(), p.sizeY(), hvColRGB<T>(0)); for (i = 0; i<p.sizeX(); i++) for (j = 0; j<p.sizeY(); j++) { val = V(p.get(i, j)); val *= scal; val += shift; update(i, j, hvColRGB<T>(T(val), T(val), T(val))); } } template <class T> template <class U, class V> hvPictRGB<T>::hvPictRGB(const hvPict<U> &p, V scal, int x, int y, int sx, int sy) { int i, j; V val; hvArray2< hvColRGB<T> >::reset(sx - x + 1, sy - y + 1, hvColRGB<T>(0)); for (i = x; i <= sx; i++) for (j = y; j <= sy; j++) { val = V(p.get(i, j)); val *= scal; this->update(i - x, j - y, hvColRGB<T>(T(val), T(val), T(val))); } } template <class T> template <class U, class V> void hvPictRGB<T>::convert(const hvPict<U> &p, V scal, int x, int y, int sx, int sy) { int i, j; V val; this->reset(sx - x + 1, sy - y + 1, hvColRGB<T>(T(0))); for (i = x; i <= sx; i++) for (j = y; j <= sy; j++) { val = V(p.get(i, j)); val *= scal; this->update(i - x, j - y, hvColRGB<T>(T(val), T(val), T(val))); } } template <class T> template <class U, class V> void hvPictRGB<T>::convertloga(const hvPict<U> &p, V loga, V max, V scal, int x, int y, int sx, int sy) { int i, j; V val; this->reset(sx - x + 1, sy - y + 1, hvColRGB<T>(T(0))); for (i = x; i <= sx; i++) for (j = y; j <= sy; j++) { val = V(p.get(i, j)); val = (V)(log(1.0 + (double)loga*(double)val / (double)max) / log((double)loga + 1.0)); if (val>V(1)) val = V(1); val *= scal; this->update(i - x, j - y, hvColRGB<T>(T(val), T(val), T(val))); } } template <class T> template <class U, class V> hvPictRGB<T>::hvPictRGB(const hvPict<U> &p, V scal, V min, V max) { int i, j; V val; hvArray2< hvColRGB<T> >::reset(p.sizeX(), p.sizeY(), hvColRGB<T>(0)); for (i = 0; i<p.sizeX(); i++) for (j = 0; j<p.sizeY(); j++) { val = V(p.get(i, j)); val = scal*(val - min) / (max - min); this->update(i, j, hvColRGB<T>(T(val), T(val), T(val))); } } template <class T> template <class U> hvPictRGB<T>::hvPictRGB(const hvPict<U> &p, const std::vector<hvColRGB<unsigned char> > &lcol) { int i, j; hvArray2< hvColRGB<T> >::reset(p.sizeX(), p.sizeY(), hvColRGB<T>(0)); for (i = 0; i<p.sizeX(); i++) for (j = 0; j<p.sizeY(); j++) { U val = p.get(i, j); this->update(i, j, lcol.at(val)); } } ///////////////////////////////////////////////////// // class hvBitmap template <class T, class U> hvBitmap::hvBitmap(const hvPict<T> &p, hvBitmap::operation op, U value) : hvBoolArray2(p.sizeX(), p.sizeY(), false) { int i, j; for (i = 0; i<p.sizeX(); i++) for (j = 0; j<p.sizeY(); j++) { switch (op) { case LESS: if (U(p.get(i, j))<value) set(i, j, true); break; case LEQUAL: if (U(p.get(i, j)) <= value) set(i, j, true); break; case EQUAL: if (U(p.get(i, j)) == value) set(i, j, true); break; case GEQUAL: if (U(p.get(i, j)) >= value) set(i, j, true); break; case GREATER: if (U(p.get(i, j))>value) set(i, j, true); break; case NOTEQUAL: if (U(p.get(i, j)) != value) set(i, j, true); break; default: break; } } } template <class T, class U> void hvBitmap::convert(const hvPict<T> &p, hvBitmap::operation op, U value) { int i, j; hvBoolArray2::reset(p.sizeX(), p.sizeY(), false); for (i = 0; i<p.sizeX(); i++) for (j = 0; j<p.sizeY(); j++) { switch (op) { case LESS: if (U(p.get(i, j))<value) set(i, j, true); break; case LEQUAL: if (U(p.get(i, j)) <= value) set(i, j, true); break; case EQUAL: if (U(p.get(i, j)) == value) set(i, j, true); break; case GEQUAL: if (U(p.get(i, j)) >= value) set(i, j, true); break; case GREATER: if (U(p.get(i, j))>value) set(i, j, true); break; case NOTEQUAL: if (U(p.get(i, j)) != value) set(i, j, true); break; default: break; } } } template <class T, class U> void hvBitmap::convert(const hvPict<T> &p, hvBitmap::operation op, int nn, U value[]) { int i, j, k; hvBoolArray2::reset(p.sizeX(), p.sizeY(), false); for (i = 0; i<p.sizeX(); i++) for (j = 0; j<p.sizeY(); j++) { for (k = 0; k<nn && get(i, j) == false; k++) { switch (op) { case LESS: if (U(p.get(i, j))<value[k]) set(i, j, true); break; case LEQUAL: if (U(p.get(i, j)) <= value[k]) set(i, j, true); break; case EQUAL: if (U(p.get(i, j)) == value[k]) set(i, j, true); break; case GEQUAL: if (U(p.get(i, j)) >= value[k]) set(i, j, true); break; case GREATER: if (U(p.get(i, j))>value[k]) set(i, j, true); break; case NOTEQUAL: if (U(p.get(i, j)) != value[k]) set(i, j, true); break; default: break; } } } } } #endif // !efined(AFX_COLOR_H__098453F0_1C38_49E9_A6F4_AABF90AA55E8__INCLUDED_)
9,080
C++
.h
249
33.586345
241
0.552706
ASTex-ICube/semiproctex
39
8
2
LGPL-2.1
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,933
hvMat3.h
ASTex-ICube_semiproctex/Semiproc_synthesis_Src/3rdParty/Externals/hview/hvMat3.h
/* * Code author: Jean-Michel Dischler */ /** * @version 1.0 */ // hvMat3.h: interface for the mat3 class. // // Defines a 3x3 matrix // main operations are: multiplication, addition, multiplication with vector // // By JMD 9/8/06 ////////////////////////////////////////////////////////////////////// #if !defined(AFX_MAT3_H__1544EA11_662A_41FD_8BD3_D7311F73A131__INCLUDED_) #define AFX_MAT3_H__1544EA11_662A_41FD_8BD3_D7311F73A131__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #ifndef M_PI #define M_PI 3.14159265358979323846 #endif #include "hvVec3.h" #include "hvMat2.h" namespace hview { template <class T> class hvMat3 // : public hviAlgebra<hvMat3<T>,T> { protected: hvVec3<T> i,j,k; public: // Constructor: defines an identity matrix hvMat3<T>():i(hvVec3<T>(1,0,0)),j(hvVec3<T>(0,1,0)),k(hvVec3<T>(0,0,1)) { } // defines a matrix by three 3D vectors each representing a column hvMat3<T>(const hvVec3<T> &a, const hvVec3<T> &b, const hvVec3<T> &c):i(a),j(b),k(c) { } // defines a matrix with a single vector u as : M=uu^t (vector u times its transposed u^t) hvMat3<T>(const hvVec3<T> &u) { hvVec3<T> v(u); i.scale(u, v.X()); j.scale(u, v.Y()); k.scale(u, v.Z()); } // Selectors : vectors corresponding to columns hvVec3<T> I() const { return i; } hvVec3<T> J() const { return j; } hvVec3<T> K() const { return k; } template <class X> hvMat3<T>(const hvMat3<X> &v) { i. template cast<X>(v.I()); j. template cast<X>(v.J()); k. template cast<X>(v.K()); } bool operator==(const hvMat3<T> &mm) const { return i==mm.i && j==mm.j && k==mm.k; } // multiply matrix by vector, result is vector hvVec3<T> mult(const hvVec3<T> &v) const { return hvVec3<T> ( i.X()*v.X()+j.X()*v.Y()+k.X()*v.Z() , i.Y()*v.X()+j.Y()*v.Y()+k.Y()*v.Z() , i.Z()*v.X()+j.Z()*v.Y()+k.Z()*v.Z() ); } hvVec3<T> operator*(const hvVec3<T> &v) const { return hvVec3<T> ( i.X()*v.X()+j.X()*v.Y()+k.X()*v.Z() , i.Y()*v.X()+j.Y()*v.Y()+k.Y()*v.Z() , i.Z()*v.X()+j.Z()*v.Y()+k.Z()*v.Z() ); } // multiply by a scalar value all components void scale(T x) { i.scale(x); j.scale(x); k.scale(x); } void operator*=(T x) { i.scale(x); j.scale(x); k.scale(x); } void operator/=(T x) { i/=x; j/=x; k/=x; } void scale(const hvMat3<T> &m, T x) { i.scale(m.i, x); j.scale(m.j, x); k.scale(m.k, x); } // multiply two matrices void mult(const hvMat3<T> &a, const hvMat3<T> &b) { hvMat3<T> r; r.i=hvVec3<T>( a.i.X()*b.i.X()+a.j.X()*b.i.Y()+a.k.X()*b.i.Z(), a.i.Y()*b.i.X()+a.j.Y()*b.i.Y()+a.k.Y()*b.i.Z(), a.i.Z()*b.i.X()+a.j.Z()*b.i.Y()+a.k.Z()*b.i.Z() ); r.j=hvVec3<T>( a.i.X()*b.j.X()+a.j.X()*b.j.Y()+a.k.X()*b.j.Z(), a.i.Y()*b.j.X()+a.j.Y()*b.j.Y()+a.k.Y()*b.j.Z(), a.i.Z()*b.j.X()+a.j.Z()*b.j.Y()+a.k.Z()*b.j.Z() ); r.k=hvVec3<T>( a.i.X()*b.k.X()+a.j.X()*b.k.Y()+a.k.X()*b.k.Z(), a.i.Y()*b.k.X()+a.j.Y()*b.k.Y()+a.k.Y()*b.k.Z(), a.i.Z()*b.k.X()+a.j.Z()*b.k.Y()+a.k.Z()*b.k.Z() ); *this = r; } // multiply two matrices hvMat3<T> operator*(const hvMat3<T> &b) const { hvMat3<T> r; r.i=hvVec3<T>( i.X()*b.i.X()+j.X()*b.i.Y()+k.X()*b.i.Z(), i.Y()*b.i.X()+j.Y()*b.i.Y()+k.Y()*b.i.Z(), i.Z()*b.i.X()+j.Z()*b.i.Y()+k.Z()*b.i.Z() ); r.j=hvVec3<T>( i.X()*b.j.X()+j.X()*b.j.Y()+k.X()*b.j.Z(), i.Y()*b.j.X()+j.Y()*b.j.Y()+k.Y()*b.j.Z(), i.Z()*b.j.X()+j.Z()*b.j.Y()+k.Z()*b.j.Z() ); r.k=hvVec3<T>( i.X()*b.k.X()+j.X()*b.k.Y()+k.X()*b.k.Z(), i.Y()*b.k.X()+j.Y()*b.k.Y()+k.Y()*b.k.Z(), i.Z()*b.k.X()+j.Z()*b.k.Y()+k.Z()*b.k.Z() ); return r; } // multiply two matrices void operator*=(const hvMat3<T> &b) { hvMat3<T> r; r.i=hvVec3<T>( i.X()*b.i.X()+j.X()*b.i.Y()+k.X()*b.i.Z(), i.Y()*b.i.X()+j.Y()*b.i.Y()+k.Y()*b.i.Z(), i.Z()*b.i.X()+j.Z()*b.i.Y()+k.Z()*b.i.Z() ); r.j=hvVec3<T>( i.X()*b.j.X()+j.X()*b.j.Y()+k.X()*b.j.Z(), i.Y()*b.j.X()+j.Y()*b.j.Y()+k.Y()*b.j.Z(), i.Z()*b.j.X()+j.Z()*b.j.Y()+k.Z()*b.j.Z() ); r.k=hvVec3<T>( i.X()*b.k.X()+j.X()*b.k.Y()+k.X()*b.k.Z(), i.Y()*b.k.X()+j.Y()*b.k.Y()+k.Y()*b.k.Z(), i.Z()*b.k.X()+j.Z()*b.k.Y()+k.Z()*b.k.Z() ); *this= r; } // divide two matrices (multiply with inverse) void div(const hvMat3<T> &a, const hvMat3<T> &b) { hvMat3<T> r(b); T d = r.det(); if (d==T(0)) { hvFatal("cannot divide by matrice!"); } r.inverse(r, d); mult(a, r); } void operator/=(const hvMat3<T> &b) { hvMat3<T> r(b); T d = r.det(); if (d==T(0)) { hvFatal("cannot divide by matrice!"); } r.inverse(r, d); mult(*this, r); } hvMat3<T> operator/(const hvMat3<T> &b) const { hvMat3<T> r(b); T d = r.det(); if (d==T(0)) { hvFatal("cannot divide by matrice!"); } r.inverse(r, d); r.mult(*this, r); return r; } // add two matrices void add(const hvMat3<T> &a, const hvMat3<T> &b) { i.add(a.i, b.i); j.add(a.j, b.j); k.add(a.k, b.k); } hvMat3<T> operator+(const hvMat3<T> &b) const { hvMat3<T> r; r.i=i+b.i; r.j=j+b.j; r.k=k+b.k; return r; } void operator+=(const hvMat3<T> &b) { i+=b.i; j+=b.j; k+=b.k; } // sub two matrices void sub(const hvMat3<T> &a, const hvMat3<T> &b) { i.sub(a.i, b.i); j.sub(a.j, b.j); k.sub(a.k, b.k); } hvMat3<T> operator-(const hvMat3<T> &b) const { hvMat3<T> r; r.i=i-b.i; r.j=j-b.j; r.k=k-b.k; return r; } void operator-=(const hvMat3<T> &b) { i-=b.i; j-=b.j; k-=b.k; } // cast mat3 as mat2 by keeping only upper left 2x2 components operator hvMat2<T>() { hvMat2<T> m ( hvVec2<T>(i.X(), i.Y()), hvVec2<T>(j.X(), j.Y()) ); return m; } // compute determinant (a scalar value) T det() const { return i.X()*(j.Y()*k.Z()-k.Y()*j.Z()) - i.Y()*(j.X()*k.Z()-k.X()*j.Z()) + i.Z()*(j.X()*k.Y()-k.X()*j.Y()); } // Inverse the matrix a, // works only if det/=0, det must be the determinant of a void inverse(const hvMat3<T> &a, T det) { if (det==T(0)) { hvFatal("cannot inverse with nul det!"); } hvVec3<T> ai(a.i), aj(a.j), ak(a.k); i = hvVec3<T>( aj.Y()*ak.Z()-ak.Y()*aj.Z(), -(aj.X()*ak.Z()-ak.X()*aj.Z()), aj.X()*ak.Y()-ak.X()*aj.Y() ); j = hvVec3<T>( -(ai.Y()*ak.Z()-ak.Y()*ai.Z()), ai.X()*ak.Z()-ak.X()*ai.Z(), -(ai.X()*ak.Y()-ak.X()*ai.Y()) ); k = hvVec3<T>( ai.Y()*aj.Z()-aj.Y()*ai.Z(), -(ai.X()*aj.Z()-aj.X()*ai.Z()), ai.X()*aj.Y()-aj.X()*ai.Y() ); scale(1.0/det); transpose(); } void inverse(const hvMat3<T> &a) { hvMat3<T> r(a); T dd = r.det(); if (dd==T(0)) { hvFatal("cannot inverse with nul det!"); } inverse(r, dd); } void inverse(T dd) { hvVec3<T> ai(i), aj(j), ak(k); if (dd==T(0)) { hvFatal("cannot inverse with nul det!"); } i = hvVec3<T>( aj.Y()*ak.Z()-ak.Y()*aj.Z(), -(aj.X()*ak.Z()-ak.X()*aj.Z()), aj.X()*ak.Y()-ak.X()*aj.Y() ); j = hvVec3<T>( -(ai.Y()*ak.Z()-ak.Y()*ai.Z()), ai.X()*ak.Z()-ak.X()*ai.Z(), -(ai.X()*ak.Y()-ak.X()*ai.Y()) ); k = hvVec3<T>( ai.Y()*aj.Z()-aj.Y()*ai.Z(), -(ai.X()*aj.Z()-aj.X()*ai.Z()), ai.X()*aj.Y()-aj.X()*ai.Y() ); scale(1.0/dd); transpose(); } void inverse() { T dd = det(); if (dd==T(0)) { hvFatal("cannot inverse with nul det!"); } inverse(dd); } // transpose matrix (symetry along the diagonal) void transpose() { hvMat3<T> r; r.i=hvVec3<T>(i.X(), j.X(), k.X()); r.j=hvVec3<T>(i.Y(), j.Y(), k.Y()); r.k=hvVec3<T>(i.Z(), j.Z(), k.Z()); *this = r; } // computes eigen vectors I,J,K from matrix "this" hvMat3<T> eigen() { /*** computing first EigenVector v1 = (a1 = theta, a2= phi in polar) ***/ int i; hvVec3<T> v1,v2,v3,v,w; T a1=T(0); T a2=T(0); for(i=2;i<20;i++) { v1=hvVec3<T>(cos(a1),sin(a1)*cos(a2),sin(a1)*sin(a2)); v=this->mult(v1); w=hvVec3<T>(-sin(a1),cos(a1)*cos(a2),cos(a1)*sin(a2)); T d1 = v.dot(w); w=hvVec3<T>(T(0),-sin(a1)*sin(a2),sin(a1)*cos(a2)); T d2= v.dot(w); a1+=M_PI*(d1<T(0) ? T(-1.0) : T(1.0))/(T)pow(2.0,(double)i); /* adjust ai */ a2+=M_PI*(d2<T(0) ? T(-1.0) : T(1.0))/(T)pow(2.0,(double)i); } v1=hvVec3<T>(cos(a1),sin(a1)*cos(a2),sin(a1)*sin(a2)); /*** computing 2nd & 3rd EigenVectors (a1 = theta in polar in plane (v2,v3) ) ***/ v2=hvVec3<T>(-v1.Y(),v1.X(),T(0)); v2.normalize(v2.norm()); v3.cross(v1,v2); v=this->mult(v2); T k1=-v.dot(v2); T k2=2.0*v.dot(v3); v=this->mult(v3); k1 += v.dot(v3); /* k1= v3.C.v3-v2.C.v2 ; k2= 2 * v3.C.v2 */ a1=T(0); for(i=2;i<20;i++) { T d1=sin(2.0*a1)*k1+cos(2.0*a1)*k2; a1 += M_PI*(d1<T(0) ? T(-1.0) : T(1.0))/(T)pow(2.0,(double)i); } v=v2*cos(a1); w=v3*sin(a1); v2=v+w; v3.cross(v1,v2); hvMat3<T> res(v1,v2,v3); res.transpose(); return res; } }; } #endif // !defined(AFX_MAT3_H__1544EA11_662A_41FD_8BD3_D7311F73A131__INCLUDED_)
8,871
C++
.h
316
24.867089
137
0.515746
ASTex-ICube/semiproctex
39
8
2
LGPL-2.1
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,935
hvBoolArray2.h
ASTex-ICube_semiproctex/Semiproc_synthesis_Src/3rdParty/Externals/hview/hvBoolArray2.h
/* * Code author: Jean-Michel Dischler */ /** * @version 1.0 */ #if !defined(AFX_BOOLARRAY2_H__09002DDD_2472_43B9_B7B6_FCB6FF1B6B0D__INCLUDED_) #define AFX_BOOLARRAY2_H__09002DDD_2472_43B9_B7B6_FCB6FF1B6B0D__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include "hvError.h" #include <assert.h> namespace hview { class hvBoolArray2 { protected: unsigned char *t; int sx, sy; public: hvBoolArray2() { t=0; sx=0; sy=0; } hvBoolArray2(int x, int y, bool nil) { t = new unsigned char [(x/8+1)*y]; if (t==0) { sx=-1; sy=-1; return; } for (int i=0; i<(x/8+1)*y; i++) t[i]=(nil==true?255:0); sx = x; sy = y; } // copy hvBoolArray2(const hvBoolArray2 &a) { hvFatal("No temporary creation of hvBoolArray2!"); } // affectation hvBoolArray2 &operator=(const hvBoolArray2 &a) { if (this != &a) { if (t!=0) delete [] t; sx = a.sx; sy = a.sy; t = new unsigned char [(sx/8+1)*sy]; if (t==0) { sx=-1; sy=-1; return *this; } for (int i=0; i<(sx/8+1)*sy; i++) t[i]=a.t[i]; } return *this; } void reset(int x, int y, bool nil) { if (t!=0) delete [] t; t = new unsigned char [(x/8+1)*y]; if (t==0) { sx=-1; sy=-1; return; } for (int i=0; i<(x/8+1)*y; i++) t[i]=(nil==true?255:0); sx = x; sy = y; } void reset(bool nil) { if (t == 0) { sx = -1; return; } for (int i = 0; i<(sx / 8 + 1)*sy; i++) t[i] = (nil == true ? 255 : 0); } void reset() { if (t!=0) delete [] t; t=0; sx=0; } // isInvalid bool isInvalid() const { return sx==-1; } // isVoid bool isVoid() const { return t==0; } // operations void clear(bool nil) { for (int i=0; i<(sx/8+1)*sy; i++) t[i]=(nil==true?255:0); } // selectors int sizeX() const { return sx; } int sizeY() const { return sy; } bool get(int x, int y) const { if(x<0 || x>=sx) { hvFatal("out of sx range!"); } if(y<0 || y>=sy) { hvFatal("out of sy range!"); } if (t==0) { hvFatal("hvArray1 is void!"); } unsigned char p=(unsigned char)(((unsigned int)x)&7); unsigned char mask = ((unsigned char)1)<<p; if (t[(((unsigned int)x)>>3)+y*(sx/8+1)] & mask ) return true; return false; } void set(int x, int y, bool v) { if(x<0 || x>=sx) { hvFatal("out of sx range!"); } if(y<0 || y>=sy) { hvFatal("out of sy range!"); } if (t==0) { hvFatal("hvArray1 is void!"); } unsigned char p=(unsigned char)(((unsigned int)x)&7); unsigned char mask = ((unsigned char)1)<<p; if (v) t[(((unsigned int)x)>>3)+y*(sx/8+1)] = t[(((unsigned int)x)>>3)+y*(sx/8+1)] | mask; else t[(((unsigned int)x)>>3)+y*(sx/8+1)] = t[(((unsigned int)x)>>3)+y*(sx/8+1)] & (~mask); } // standard boolean orperators void operator|=(const hvBoolArray2 &x) { if (x.sizeX()!=sizeX()) hvFatal("not same sizeX in hvBoolArray1::operator|"); if (x.sizeY()!=sizeY()) hvFatal("not same sizeY in hvBoolArray1::operator|"); for (int i=0; i<(sx/8+1)*sy; i++) t[i] |= x.t[i]; } void operator&=(const hvBoolArray2 &x) { assert(x.sizeX()==sizeX()); assert(x.sizeY()==sizeY()); for (int i=0; i<(sx/8+1)*sy; i++) t[i] &= x.t[i]; } void operator~() { for (int i=0; i<(sx/8+1)*sy; i++) t[i] = ~t[i]; } void operator^=(const hvBoolArray2 &x) { if (x.sizeX()!=sizeX()) hvFatal("not same sizeX in hvBoolArray1::operator|"); if (x.sizeY()!=sizeY()) hvFatal("not same sizeY in hvBoolArray1::operator|"); for (int i=0; i<(sx/8+1)*sy; i++) t[i] ^= x.t[i]; } ~hvBoolArray2() { if (t!=0) delete [] t;} }; } #endif // !defined(AFX_ARRAY1_H__09002DDD_2472_43B9_B7B6_FCB6FF1B6B0D__INCLUDED_)
3,559
C++
.h
136
23.647059
93
0.587959
ASTex-ICube/semiproctex
39
8
2
LGPL-2.1
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,936
hvVec.h
ASTex-ICube_semiproctex/Semiproc_synthesis_Src/3rdParty/Externals/hview/hvVec.h
/* * Code author: Jean-Michel Dischler */ /** * @version 1.0 */ // hvVec.h: interface for the vector class. // ////////////////////////////////////////////////////////////////////// #if !defined(AFX_VECTOR_H__9621FBEC_AB7C_4F9F_B7E3_56541A01CC32__INCLUDED_) #define AFX_VECTOR_H__9621FBEC_AB7C_4F9F_B7E3_56541A01CC32__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include <math.h> #include "hvError.h" namespace hview { template <class T, int size> class hvVec { protected: T v[size]; public: hvVec<T,size>(T nil) { for (int i=0; i<size; i++) v[i]=nil; } hvVec<T,size>() { for (int i=0; i<size; i++) v[i]=(T)0; } T &operator[](int i) { if (i<0 || i>=size) { hvFatal("access out of range in vector!"); } return v[i]; } // copy hvVec<T,size>(const hvVec<T,size> &a) { for (int i=0; i<size; i++) v[i]=a.v[i]; //printf("warning: temporary creation of vec<T,int>!\n"); } T *data() { return v; } hvVec<T,size> &operator=(const hvVec<T,size> &a) { if (this != &a) { for (int i=0; i<size; i++) v[i]=a.v[i]; } return *this; } // int size() { return size; } void clear(T x=T(0)) { for (int i=0; i<size; i++) v[i]=x; } /////// operations void add(const hvVec<T,size> &a, const hvVec<T,size> &b) { for (int i=0; i<size; i++) { v[i]=a.v[i]+b.v[i]; } } hvVec<T,size> operator+(const hvVec<T,size> &a) const { hvVec<T,size> r; for (int i=0; i<size; i++) { r.v[i]= v[i]+a.v[i]; } return r; } void operator+=(const hvVec<T,size> &a) { for (int i=0; i<size; i++) { v[i]+= a.v[i]; } } void sub(const hvVec<T,size> &a, const hvVec<T,size> &b) { for (int i=0; i<size; i++) { v[i]=a.v[i]-b.v[i]; } } hvVec<T,size> operator-(const hvVec<T,size> &b) const { hvVec<T,size> r; for (int i=0; i<size; i++) { r.v[i]= v[i]-b.v[i]; } return r; } void operator-=(const hvVec<T,size> &b) { for (int i=0; i<size; i++) { v[i]-= b.v[i]; } } void mult(const hvVec<T,size> &a, const hvVec<T,size> &b) { for (int i=0; i<size; i++) { v[i]=a.v[i]*b.v[i]; } } hvVec<T,size> operator*(const hvVec<T,size> &b) const { hvVec<T,size> r; for (int i=0; i<size; i++) { r.v[i]= v[i]*b.v[i]; } return r; } void operator*=(const hvVec<T,size> &b) { for (int i=0; i<size; i++) { v[i]*= b.v[i]; } } void operator*=(T x) { for (int i=0; i<size; i++) { v[i]*= x; } } template <class X> void operator*=(X x) { for (int i=0; i<size; i++) { v[i]= (T)((X)v[i]*x); } } void div(const hvVec<T,size> &a, const hvVec<T,size> &b) { for (int i=0; i<size; i++) { v[i]=a.v[i]/b.v[i]; } } hvVec<T,size> operator/(const hvVec<T,size> &b) const { hvVec<T,size> r; for (int i=0; i<size; i++) { r.v[i]= v[i]/b.v[i]; } return r; } void operator/=(const hvVec<T,size> &b) { for (int i=0; i<size; i++) { v[i] /= b.v[i]; } } void operator/=(T x) { for (int i=0; i<size; i++) { v[i]/= x; } } template <class X> void operator/=(X x) { for (int i=0; i<size; i++) { v[i]= (T)((X)v[i]/x); } } // scale by scalar value void scale(const hvVec<T,size> &a, T k) { for (int i=0; i<size; i++) v[i]=a.v[i]*k; } void scale(T k) { for (int i=0; i<size; i++) v[i]*=k; } template <class X> void scale(X k) { for (int i=0; i<size; i++) v[i]= (T)((X)v[i]*k); } // divide by scalar, this scalar cannot be null void normalize(T norme) { for (int i=0; i<size; i++) v[i]/=norme; } void divScale(T k) { for (int i=0; i<size; i++) v[i]/=k; } template <class X> void divScale(X k) { for (int i=0; i<size; i++) v[i]= (T)((X)v[i]/k); } // absolute value component by component void abs() { for (int i=0; i<size; i++) if (v[i]<(T)0) v[i] = -v[i]; } // dot product (produit scalaire) T dot(const hvVec<T,size> &a) const { T r=0; for (int i=0; i<size; i++) r+=(v[i]*a.v[i]); return r; } // opposite vector void reverse() { for (int i=0; i<size; i++) v[i]=-v[i]; } hvVec<T,size> operator-() { hvVec<T,size> r=*this; r.reverse(); return r; } /* linear interpolation between v1 and v2 according to t (between 0 and 1), if t=0 result is v1, if t=1 result is v2 result is not normalized */ template <class X> void interpolate(const hvVec<T,size> &v1, const hvVec<T,size> &v2, X t) { for (int i=0; i<size; i++) { v[i] = (T)(((X)1.0-t)*(X)v1.v[i] + t*(X)v2.v[i]); } } /* linear interpolation between v1 and v2 according to vector t; each component of t is between 0 and 1 and gives coefficient, result is not normalized */ template <class X> void interpolate(const hvVec<T,size> &v1, const hvVec<T,size> &v2, const hvVec<X,size> &t) { for (int i=0; i<size; i++) { v[i] = (T)(((X)1.0-t.v[i])*(X)v1.v[i] + t.v[i]*(X)v2.v[i]); } } /* compares component by component and keeps the min one result is not normalized */ void keepMin(const hvVec<T,size> &v1, const hvVec<T,size> &v2) { for (int i=0; i<size; i++) if (v1.v[i]<v2.v[i]) v[i] = v1.v[i]; else v[i] = v2.v[i]; } /* compares component by component and keeps the max one result is not normalized */ void keepMax(const hvVec<T,size> &v1, const hvVec<T,size> &v2) { for (int i=0; i<size; i++) if (v1.v[i]>v2.v[i]) v[i] = v1.v[i]; else v[i] = v2.v[i]; } /* returns the largest / smallest component */ T maxCoord() const { T m=v[0]; for (int i=0; i<size; i++) if (v[i]>m) m=v[i]; return m; } T minCoord() const { T m=v[0]; for (int i=0; i<size; i++) if (v[i]<m) m=v[i]; return m; } /* computes the norm (vector length) */ T normSquared() const { T m=0; for (int i=0; i<size; i++) m+=v[i]*v[i]; return m; } double normSquaredDouble() const { double m=0; for (int i=0; i<size; i++) m+=(double)v[i]*(double)v[i]; return m; } T norm() const { return (T)sqrt(normSquaredDouble()); } bool equals(const hvVec<T,size> &tt) { for (int i=0; i<size; i++) if (v[i]!=tt.v[i]) return false; return true; } bool operator==(const hvVec<T,size> &tt) { for (int i=0; i<size; i++) if (v[i]!=tt.v[i]) return false; return true; } }; } #endif // !defined(AFX_VECTOR_H__9621FBEC_AB7C_4F9F_B7E3_56541A01CC32__INCLUDED_)
6,062
C++
.h
194
28.670103
116
0.576204
ASTex-ICube/semiproctex
39
8
2
LGPL-2.1
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,937
hvField1.h
ASTex-ICube_semiproctex/Semiproc_synthesis_Src/3rdParty/Externals/hview/hvField1.h
/* * Code author: Jean-Michel Dischler */ /** * @version 1.0 */ #if !defined(AFX_FIELD1D_H__B6AC0A32_75EF_428E_BC10_6219F619FA29__INCLUDED_) #define AFX_FIELD1D_H__B6AC0A32_75EF_428E_BC10_6219F619FA29__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 //////////////////////////////////////////// /* Field1<X>: is a regular grid of dimension N=1 where each grid point contains elements of type X (scalars or vectors). X : is either a vector : hvVec3<U> or a scalar */ //////////////////////////////////////////// //////////////////////////////////////////// #include "hvField.h" #include "hvArray1.h" namespace hview { template <class X> class hvField1 : public virtual hvField<X>, public virtual hvArray1<X> { public: hvField1<X>(int s, X nil):hvField<X>(nil),hvArray1<X>(s,nil) { hvField<X>::loop[0]=hvField<X>::CLAMP; } hvField1<X>():hvField<X>(),hvArray1<X>() { hvField<X>::loop[0]=hvField<X>::CLAMP; } virtual int size(int dim) const { if (dim!=0) hvFatal("dim must be 0 in hvField1::size(int dim)"); return hvArray1< X>::size(); } int sizeX() const { return hvArray1< X>::size(); } virtual int dimension() const { return 1; } virtual X operator()(int ind[]) const { int i; if (ind[0]<0||ind[0]>=hvArray1<X>::size()) { if (hvField<X>::loop[0]==hvField<X>::CLAMP) return hvField<X>::clampvalue; i = ind[0]%hvArray1<X>::size(); if (hvField<X>::loop[0]==hvField<X>::MIRROR && (ind[0]/hvArray1<X>::size())%2==1) i = hvArray1<X>::size()-i-1; } else i=ind[0]; return hvArray1<X>::get(i); } virtual X get(int ind[]) const { int i; if (ind[0]<0||ind[0]>=hvArray1<X>::size()) { if (hvField<X>::loop[0]==hvField<X>::CLAMP) return hvField<X>::clampvalue; i = ind[0]%hvArray1<X>::size(); if (hvField<X>::loop[0]==hvField<X>::MIRROR && (ind[0]/hvArray1<X>::size())%2==1) i = hvArray1<X>::size()-i-1; } else i=ind[0]; return hvArray1<X>::get(i); } virtual void update(int ind[], X val) { if (ind[0]<0||ind[0]>=hvArray1<X>::size()) return; hvArray1<X>::update(ind[0], val); } virtual void clear(X k) { for (int i=0; i<hvArray1<X>::size(); i++) hvArray1<X>::t[i] = k; } virtual void scale(int k) { for (int i=0; i<hvArray1<X>::size(); i++) { hvArray1<X>::t[i] *= k; } } virtual void scale(float k) { for (int i=0; i<hvArray1<X>::size(); i++) { hvArray1<X>::t[i] *= k; } } virtual void scale(double k) { for (int i=0; i<hvArray1<X>::size(); i++) { hvArray1<X>::t[i] *= k; } } virtual void add(hvField<X> *f) { if (f->dimension()!=1 || hvArray1<X>::size()!=f->size(0) ) { hvFatal("cannot add in hvField1"); return; } for (int i=0; i<hvArray1<X>::size(); i++) hvArray1<X>::t[i] += f->get(&i); } virtual void clone(hvField<X> *f) { if (f->dimension()!=1) { hvFatal("cannot clone in hvField1"); return; } if ( hvArray1<X>::size()!=f->size(0) ) this->reset(f->size(0)); hvField<X>::clampvalue = f->getClampValue(); hvField<X>::loop[0]=f->getLoop(0); for (int i=0; i<hvArray1<X>::size(); i++) hvArray1<X>::t[i] = f->get(&i); } virtual void shrink(hvField<X> *f) { int ind1, ind2; if (f->dimension()!=1) { hvFatal("cannot clone in hvField1"); return; } this->reset(f->size(0)/2); hvField<X>::clampvalue = f->getClampValue(); hvField<X>::loop[0]=f->getLoop(0); for (int i=0; i<hvArray1<X>::size(); i++) { ind1=i*2; ind2=i*2+1; X cste(2); X sum = f->get(&ind1); X val = f->get(&ind2); sum += val; sum /= cste; hvArray1<X>::update(i,sum); } } template <class Y> void convolve(hvField<X> *f, hvField<Y> *mask) { if (mask->dimension()!=1) { hvFatal("cannot convolve in hvScalarField1"); return; } if (f->dimension()!=1) { hvFatal("cannot convolve in hvScalarField1"); return; } if ( hvArray1<X>::size()!=f->size(0) ) this->reset(f->size(0)); int s = mask->size(0)/2; for (int i=0; i<hvArray1<X>::size(); i++) { int ind = i-s, j=0; Y vv=Y(f->get(&ind))*mask->get(&j); for (j=1; j<mask->size(0); j++) { ind = i+j-s; vv += Y(f->get(&ind))*mask->get(&j); } update(&i, X(vv)); } } virtual void derivative(hvField<X> *f, int dim) { if (dim!=0) hvFatal("dim must be 0 in hvField1::derivative(...)"); if (f->dimension()!=1) { hvFatal("cannot compute gradient in hvField1"); return; } if ( hvArray1<X>::size()!=f->size(0) ) this->reset(f->size(0)); for (int i=0; i<hvArray1<X>::size(); i++) { int ind=i+1; X sum = f->get(&ind); sum -= f->get(&i); hvArray1<X>::update(i,sum); } } template <class Y> hvArray1<hvPair<Y,Y> > *fft(bool centred, Y scal, Y offset) { int i; X rr; int pow_2=1, nn=2; while(nn<sizeX()) { pow_2=pow_2+1; nn *= 2; } hvArray1<hvPair<Y,Y> > *ft = new hvArray1<hvPair<Y,Y> >(nn, hvPair<Y,Y>(Y(0),Y(0))); for (i=0; i<nn; i++) { if (i<sizeX()) rr = get(&i); else rr = X(0); Y xx = (Y(rr)-offset) / scal; ft->update(i, hvPair<Y,Y>(centred && i%2==1 ? Y(0)-xx: xx,Y(0))); } hvArray1<Y>::fft(*ft,pow_2,1,0,true); return ft; } }; } #endif // !defined(AFX_SCAL_H__B6AC0A32_75EF_428E_BC10_6219F619FA29__INCLUDED_)
5,114
C++
.h
158
29.449367
117
0.585781
ASTex-ICube/semiproctex
39
8
2
LGPL-2.1
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,940
hvList.h
ASTex-ICube_semiproctex/Semiproc_synthesis_Src/3rdParty/Externals/hview/hvList.h
/* * Code author: Jean-Michel Dischler */ /** * @version 1.0 */ // List.h: interface for the List class. // ////////////////////////////////////////////////////////////////////// #if !defined(AFX_LIST_H__297E9DA5_208E_4B76_9FA8_57C002399BE0__INCLUDED_) #define AFX_LIST_H__297E9DA5_208E_4B76_9FA8_57C002399BE0__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include <vector> #include "hvError.h" namespace hview { template <class T> class hvSortedList : public std::vector<T> { public: hvSortedList<T>():std::vector<T>() { } hvSortedList<T>(unsigned long m): std::vector<T>(m) { } // copy hvSortedList<T>(const hvSortedList<T> &a) { hvFatal("no temporary creation of hvSortedList<T>!"); } // affectation hvSortedList<T> &operator=(const hvSortedList<T> &a){ hvFatal("no affectation of hvSortedList<T>, use operator <copy>!"); } void sort() { partialSort(0,this->size()-1); } void partialSort(int start, int end); void pointerSort() { partialPointerSort(0, this->size()-1); } void partialPointerSort(int start, int end); int pushSorted(T e); // require operator <= int pushSortedBound(T e, int n); // require operator <= int pushSortedSet(T e); // require operator <= and == int search(T e) const; // require operator and == int searchSorted(T e) const; // require operator <= and == int searchSortedPos(T e, int start, int end) const; // require operator <= and == int searchSortedPosSet(T e, int start, int end) const; // require operator <= and == void swap(int pos1, int pos2); void reverse(int start, int end); void reverse() { reverse(0, this->size() - 1); } }; template <class T> void hvSortedList<T>::partialSort(int start, int end) { int a,b; int m; T x; if (start>=end) return; a=start; b=end; m=(start+end)>>1; x = this->at(m); while (a<=b) { while ( this->at(a)<x ) a++; while ( x<this->at(b) ) b--; if (a<=b) { swap(a,b); a++; b--; } } partialSort(start,b); partialSort(a,end); } template <class T> void hvSortedList<T>::partialPointerSort(int start, int end) { int a,b; int m; T x; if (start>=end) return; a=start; b=end; m=(start+end)>>1; x = this->at(m); while (a<=b) { while ( x->compare(this->at(a),x)<0 ) a++; while ( x->compare(x, this->at(b))<0 ) b--; if (a<=b) { swap(a,b); a++; b--; } } partialSort(start,b); partialSort(a,end); } template <class T> int hvSortedList<T>::pushSorted(T e) { int pos; if (std::vector<T>::size()==0) { this->push_back(e); return(0); } pos = this->searchSortedPos(e,0,this->size()); if (pos == -1) return(-1); std::vector<int>::iterator it; it = this->begin(); this->insert(it+pos,e); return(pos); } template <class T> int hvSortedList<T>::pushSortedBound(T e, int n) { int pos; if (std::vector<T>::size() == 0) { this->push_back(e); return(0); } pos = this->searchSortedPos(e, 0, this->size()); if (pos == -1) return(-1); if (this->size() == n) { if (pos == this->size()) return -1; else this->pop_back(); } std::vector<int>::iterator it; it = this->begin(); this->insert(it + pos, e); return(pos); } template <class T> int hvSortedList<T>::pushSortedSet(T e) { int pos; if (std::vector<T>::size() ==0) { this->push_back(e); return(0); } pos = this->searchSortedPosSet(e,0, this->size()); if (pos == -1) return(-1); std::vector<int>::iterator it; it = this->begin(); this->insert(it + pos, e); return(pos); } template <class T> int hvSortedList<T>::search(T e) const { long i; if (std::vector<T>::size() == 0) return(-1); for (i = 0; i<std::vector<T>::size(); i++) if (std::vector<T>::at(i) == e) return(i); return(-1); } template <class T> int hvSortedList<T>::searchSorted(T e) const { long i; if (std::vector<T>::size() ==0) return(-1); i=this->searchSortedPos(e,0, this->size() -1); if (std::vector<T>::at(i)==e) return(i); else return(-1); } template <class T> int hvSortedList<T>::searchSortedPos(T e, int start, int end) const { int m; while (start < end) { m=(start+end)>>1; if (std::vector<T>::at(m)<e ) start=m+1; else end=m; } return(start); } template <class T> int hvSortedList<T>::searchSortedPosSet(T e, int start, int end) const { int m,ee; ee=end; while (start < end) { m=(start+end)>>1; if (std::vector<T>::at(m) == e) return(-1); else if (std::vector<T>::at(m)<e ) start=m+1; else end=m; } if (start==ee) return start; if (std::vector<T>::at(start) == e) return(-1); else return(start); } template <class T> void hvSortedList<T>::swap(int pos1, int pos2) { T x; if (pos1==pos2) return; x= std::vector<T>::at(pos1); std::vector<T>::operator[](pos1) = std::vector<T>::at(pos2); std::vector<T>::operator[](pos2) = x; } template <class T> void hvSortedList<T>::reverse(int start, int end) { int i; //if (val == 0) { hvFatal("cannot reverse, hvList is void"); } if ((start<0) || ((unsigned)start>this->size())) { std::cout<<"illegal start in reverse hvSortedList\n"; hvFatal("out of range"); } if ((end<0) || ((unsigned)end>this->size()) || (end<start)) { std::cout << "illegal end in reverse hvSortedList\n"; hvFatal("out of range"); } for (i = 0; i <= ((end - start) >> 1); i++) swap(i + start, end - i); } } #endif // !defined(AFX_LIST_H__297E9DA5_208E_4B76_9FA8_57C002399BE0__INCLUDED_)
5,479
C++
.h
179
27.424581
143
0.610562
ASTex-ICube/semiproctex
39
8
2
LGPL-2.1
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,941
hvArray1.h
ASTex-ICube_semiproctex/Semiproc_synthesis_Src/3rdParty/Externals/hview/hvArray1.h
/* * Code author: Jean-Michel Dischler */ /** * @version 1.0 */ #if !defined(AFX_ARRAY1_H__09002DDD_2472_43B9_B7B6_FCB6FF1B6B0D__INCLUDED_) #define AFX_ARRAY1_H__09002DDD_2472_43B9_B7B6_FCB6FF1B6B0D__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include <math.h> #include "hvError.h" #include "hvPair.h" #ifndef M_PI #define M_PI 3.14159265358979323846 #endif namespace hview { template <class T> class hvArray1 { protected: T *t; int sx; public: hvArray1() { t=0; sx=0; } hvArray1(int x, T nil) { t = new T[x]; if (t==0) { sx=-1; return; } for (int i=0; i<x; i++) t[i]=nil; sx = x; } T *data() const { return t; } // copy hvArray1(const hvArray1 &a) { hvFatal("No temporary creation of hvArray1!"); } // affectation hvArray1 &operator=(const hvArray1 &a) { if (this != &a) { if (t!=0) delete [] t; if (a.isInvalid()) { t=0; sx=-1; return *this; } sx = a.sx; t = new T [sx]; if (t==0) { sx=-1; return *this; } for (int i=0; i<sx; i++) t[i]=a.t[i]; } return *this; } void reset(int x, T nil) { if (t!=0) delete [] t; t = new T[x]; if (t==0) { sx=-1; return; } for (int i=0; i<x; i++) t[i]=nil; sx = x; } void reset(int x) { if (t!=0) delete [] t; t = new T[x]; if (t==0) { sx=-1; return; } sx = x; } void reset() { if (t!=0) delete [] t; t=0; sx=0; } // isInvalid bool isInvalid() const { return sx==-1; } // isVoid bool isVoid() const { return t==0; } // operations void clear(T nil) { for (int i=0; i<sx; i++) t[i]=nil; } // selectors int size() const { return sx; } T &operator[](int x) { if(x<0 || x>=sx) { hvFatal("out of range!"); } if (t==0) { hvFatal("hvArray1 is void!"); } return t[x]; } T get(int x) const { assert(!(x < 0 || x >= sx)); assert(t != NULL); return t[x]; } T *getPointer(int x) { if(x<0 || x>=sx) { hvFatal("out of range!"); } if (t==0) { hvFatal("hvArray1 is void!"); } return t+x; } void update(int x, T val) { assert(!(x < 0 || x >= sx)); assert(t != NULL); t[x]=val; } template <class U> void updateRange(int start, int end, U *val) { assert(!(start < 0 || start >= sx)); assert(!(end < 0 || end >= sx)); assert(t != NULL); for (int i=start; i<=end; i++) t[i]=T(val[i-start]); } ~hvArray1() { if (t!=0) delete [] t;} // FFT algorithm // F is pointer to pairs (integer, imaginary) part of complex numbers of type T // N is such that 2^N is the size of the array F static void fft(hvArray1<hvPair<T,T> > &F, int N, int s, int id, bool divn) { int n,i,j,k,l,nv2,ip; hvPair<T,T> u,w,tmp; n = 1<<N; /* n=2^N */ nv2=n>>1; /* nv2=2^(N-1) */ j=1; for (i=1; i<=n-1; i++) { if (i<j) { tmp=F[(j-1)*s+id]; F[(j-1)*s+id]=F[(i-1)*s+id]; F[(i-1)*s+id]=tmp; } k=nv2; while(k<j) { j=j-k; k=k>>1; } j=j+k; } for (l=1; l<=N; l++) { int le = 1<<l; int le1 = le>>1; u=hvPair<T,T>(T(1.0),T(0.0)); double a = M_PI/(double)le1; w=hvPair<T,T>(T(cos(a)),T(-sin(a))); for (j=1; j<=le1; j++) { for (i=j; i<=n; i+=le) { ip=i+le1; tmp = hvPair<T,T>(F[((ip-1)*s+id)].getLeft()*u.getLeft()-F[((ip-1)*s+id)].getRight()*u.getRight(),F[((ip-1)*s+id)].getLeft()*u.getRight()+F[((ip-1)*s+id)].getRight()*u.getLeft()); F[((ip-1)*s+id)]= hvPair<T,T>(F[((i-1)*s+id)].getLeft()-tmp.getLeft(), F[((i-1)*s+id)].getRight()-tmp.getRight()); F[((i-1)*s+id)]= hvPair<T,T>(F[((i-1)*s+id)].getLeft()+tmp.getLeft(), F[((i-1)*s+id)].getRight()+tmp.getRight()); } u = hvPair<T,T>(u.getLeft()*w.getLeft()-u.getRight()*w.getRight(), u.getLeft()*w.getRight()+u.getRight()*w.getLeft()); } } if (divn) { double ff = 1.0/(double)n; for (i=1;i<=n; i++) F[((i-1)*s+id)]= hvPair<T,T>(F[((i-1)*s+id)].getLeft()*ff, F[((i-1)*s+id)].getRight()*ff); } } }; } #endif // !defined(AFX_ARRAY1_H__09002DDD_2472_43B9_B7B6_FCB6FF1B6B0D__INCLUDED_)
3,916
C++
.h
170
20.405882
183
0.557016
ASTex-ICube/semiproctex
39
8
2
LGPL-2.1
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,944
hvFrame3.h
ASTex-ICube_semiproctex/Semiproc_synthesis_Src/3rdParty/Externals/hview/hvFrame3.h
/* * Code author: Jean-Michel Dischler */ /** * @version 1.0 */ // hvFrame3.h: interface for the frame3 class. // // hvFrame3: defines a frame for an euclidian 3D space // a frame is composed of an origin point and 3 orthonormal vectors // frame3 is composed of a vec3<T> and a mat3<T> // main operations allow to change points and vectors from one frame to another // by extracting transfer matrices // // By JMD 10/8/06 ////////////////////////////////////////////////////////////////////// #if !defined(AFX_FRAME3_H__824D3162_521A_4FD7_9D86_19B3BA026926__INCLUDED_) #define AFX_FRAME3_H__824D3162_521A_4FD7_9D86_19B3BA026926__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include "hvMat4.h" namespace hview { template <class T> class hvFrame3 { protected: hvVec3<T> ori; hvMat3<T> mat; public: // constructors hvFrame3<T>():mat(), ori(hvVec3<T>(T(0),T(0),T(0))) { } hvFrame3(const hvVec3<T> &o, const hvVec3<T> &x, const hvVec3<T> &y, const hvVec3<T> &z) : mat(x,y,z),ori(o) { } hvFrame3(const hvVec3<T> &o):mat(), ori(o) { } hvFrame3(const hvVec3<T> &o, const hvMat3<T> &m):mat(m), ori(o) { } void setOrigin(const hvVec3<T> &o) { ori=o; } // selectors hvVec3<T> origin() const { return ori; } hvVec3<T> I() const { return mat.I(); } hvVec3<T> J() const { return mat.J(); } hvVec3<T> K() const { return mat.K(); } hvVec3<T> coordinates(const hvVec3<T> &pt) const { hvVec3<T> p; p.PVec(ori,pt); return hvVec3<T>(p.dot(this->I())/ this->I().normSquared(),p.dot(this->J())/ this->J().normSquared(),p.dot(this->K())/ this->K().normSquared()); } T det() const { return mat.det(); } bool operator==(const hvFrame3<T> &f) const { return ori==f.ori && mat==f.mat; } // Compute change of frame matrix (dimension 3) for vectors // Resulting matrix allows to express a vector given in base coordinates : // (1,0,0);(0,1,0);(0,0,1) into the frame coordinates hvMat3<T> changeToFrame3(T det) const { hvMat3<T> r; r.inverse(mat, det); return r; } // Compute change of frame matrix (dimension 3) for vectors // Resulting matrix allows to express a vector given in frame coordinates // into basic coordinates, e.g. (1,0,0);(0,1,0);(0,0,1) hvMat3<T> changeFromFrame3() const { return mat; } // Compute change of frame matrix (dimension 4) for points // Resulting matrix allows to express a point given in base coordinates : // O(0,0,0);i(1,0,0);j(0,1,0);k(0,0,1) into the frame coordinates hvMat4<T> changeToFrame4(T det) const { hvVec3<T> io=ori; io.reverse(); hvMat4<T> m1(hvMat3<T>(), io); hvMat3<T> r=this->changeToFrame3(det); hvMat4<T> m2(r); m1.mult(m1, m2); return m1; } // Compute change of frame matrix (dimension 4) for points // Resulting matrix allows to express a point given in frame coordinates // into basic coordinates, e.g. O(0,0,0);i(1,0,0);j(0,1,0);k(0,0,1) hvMat4<T> changeFromFrame4() const { hvMat3<T> r=this->changeFromFrame3(); hvMat4<T> m1(r); hvVec3<T> io=ori; hvMat4<T> m2(hvMat3<T>(), io); m1.mult(m1, m2); return m1; } }; } #endif // !defined(AFX_FRAME3_H__824D3162_521A_4FD7_9D86_19B3BA026926__INCLUDED_)
3,168
C++
.h
93
31.763441
146
0.665029
ASTex-ICube/semiproctex
39
8
2
LGPL-2.1
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,946
hvField.h
ASTex-ICube_semiproctex/Semiproc_synthesis_Src/3rdParty/Externals/hview/hvField.h
/* * Code author: Jean-Michel Dischler */ /** * @version 1.0 */ #if !defined(AFX_FIELD_H__B6AC0A32_75EF_428E_BC10_6219F619FA29__INCLUDED_) #define AFX_FIELD_H__B6AC0A32_75EF_428E_BC10_6219F619FA29__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 //////////////////////////////////////////// /* Field<X>: is an array of dimension N=1,2,3 containing elements of type X. X : is a scalable (implements hviAlgebra operators) */ //////////////////////////////////////////// //////////////////////////////////////////// #include <math.h> #include "hvError.h" namespace hview { const unsigned int MAX_FIELD_DIMENSION=3; template <class X> class hvField { public: enum bordertype { CLAMP, LOOP, MIRROR }; protected: bordertype loop[MAX_FIELD_DIMENSION]; X clampvalue; public: hvField<X>() { clampvalue=X(0); } hvField<X>(const X &cl) { clampvalue=cl; } // copy hvField<X>(const hvField<X> &a) { hvFatal("No temporary creation of hvField!"); } hvField<X> &operator=(hvField<X> &a) { hvFatal("No operator= for hvField!"); return a; } static int index(int i, bordertype b, int s) { int id=i; if (b==CLAMP) return i; while (id<0) { if (b==MIRROR) id=-id; else id += s; } if (b==MIRROR && (id/s)%2==1) id = s-(id%s)-1; else id = id%s; return id; } virtual void update(int ind[], X val) =0; virtual void clear(X val) =0; virtual int size(int dim) const =0; X getClampValue() const { return clampvalue; } bordertype getLoop(int dim) { if (dim>=dimension()) hvFatal("too high dimension in hvField<X>::getLoop"); return loop[dim]; } virtual void setLoop(int dim, bordertype v) { if (dim>=dimension()) hvFatal("too high dimension in hvField<X>::setLoop"); loop[dim]=v; } virtual void setClampValue(X v) { clampvalue=v; } virtual int dimension() const = 0; virtual X operator()(int ind[]) const = 0; virtual X get(int ind[]) const = 0; virtual void scale(int k) =0; virtual void scale(float k) =0; virtual void scale(double k) =0; virtual void add(hvField<X> *f) =0; virtual void clone(hvField<X> *f) =0; virtual void shrink(hvField<X> *f) =0; virtual void derivative(hvField<X> *f, int dim) =0; }; } #endif // !defined(AFX_SCAL_H__B6AC0A32_75EF_428E_BC10_6219F619FA29__INCLUDED_)
2,278
C++
.h
79
26.64557
79
0.650436
ASTex-ICube/semiproctex
39
8
2
LGPL-2.1
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,947
hvPair.h
ASTex-ICube_semiproctex/Semiproc_synthesis_Src/3rdParty/Externals/hview/hvPair.h
/* * Code author: Jean-Michel Dischler */ /** * @version 1.0 */ // hvPair.h: interface for the pair class. // ////////////////////////////////////////////////////////////////////// #if !defined(AFX_PAIR_H__09002DDD_2472_43B9_B7B6_FCB6FF1B6B0D__INCLUDED_) #define AFX_PAIR_H__09002DDD_2472_43B9_B7B6_FCB6FF1B6B0D__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include "hvError.h" namespace hview { template <class T, class U> class hvPair { protected: T left; U right; public: hvPair() { left=T(0); right=U(0); } hvPair(const T &x, const U &y) { left=x; right=y; } void setLeft(const T &x) { left=x; } void setRight(const U &x) { right=x; } T getLeft() { return left; } U getRight() { return right; } bool operator==(const hvPair<T,U> &pp) const { return left==pp.left && right==pp.right; } // complex numbers double mod() { return sqrt((double)left*(double)left+(double)right*(double)right); } double energy() { return (double)left*(double)left+(double)right*(double)right; } double phase() { double rr, r = (double)left, i = (double)right; if (r==0.0 && i==0.0) return(0.0); if ((r>0.0?r:-r)>(i>0.0?i:-i)) { rr = i/r; if (r<0.0) rr = M_PI+atan(rr); else rr = atan(rr); } else { rr = r/i; if (i>0.0) rr = M_PI/2.0-atan(rr); else rr = 3.0*M_PI/2.0-atan(rr); } if (rr>M_PI) return(rr-2.0*M_PI); else if (rr<-M_PI) return(rr+2.0*M_PI); return(rr); } }; } #endif // !defined(AFX_PAIR_H__09002DDD_2472_43B9_B7B6_FCB6FF1B6B0D__INCLUDED_)
1,526
C++
.h
58
24.189655
85
0.613058
ASTex-ICube/semiproctex
39
8
2
LGPL-2.1
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,948
MyThreadPool.h
ASTex-ICube_semiproctex/Semiproc_synthesis_Src/3rdParty/Externals/hview/MyThreadPool.h
/* * Code author: Frederic Larue */ /** * @version 1.0 */ #ifndef __MYTHREADPOOL_H__ #define __MYTHREADPOOL_H__ #include <future> #include <queue> #include <functional> class MyThreadPool { public: using Task = std::packaged_task<void()>; // Some data associated to each thread. struct ThreadData { int id; // Could use thread::id, but this is filled before the thread is started int nThreads; // Total number of threads. std::thread t; // The thread object std::queue<Task> tasks; // The job queue std::condition_variable cv; // The condition variable to wait for threads std::mutex m; // Mutex used for avoiding data races bool stop; // When set, this flag tells the thread that it should exit }; private: // The thread function executed by each thread static inline void threadFunc( ThreadData* pData ) { std::unique_lock<std::mutex> l( pData->m, std::defer_lock ); while( true ) { l.lock(); // Wait until the queue won't be empty or stop is signaled pData->cv.wait(l, [pData] () { return (pData->stop || !pData->tasks.empty()); } ); // Stop was signaled, let's exit the thread if (pData->stop) { return; } // Pop one task from the queue... Task task = std::move( pData->tasks.front() ); pData->tasks.pop(); l.unlock(); // Execute the task! task(); } } int nThreads; ThreadData* threads; std::vector< std::future<void> > futures; public: inline MyThreadPool() { nThreads = (int) std::thread::hardware_concurrency(); threads = new ThreadData [ nThreads ]; for( int i=0; i<nThreads; ++i ) { threads[i].stop = false; threads[i].id = i; threads[i].nThreads = nThreads; threads[i].t = std::thread( threadFunc, threads+i ); } } template <typename TFunc> inline void AppendTask( const TFunc& func ) { for( int i=0; i<nThreads; ++i ) { // Function that creates a simple task Task task( std::bind( func, threads+i ) ); futures.push_back( task.get_future() ); std::unique_lock<std::mutex> l( threads[i].m ); threads[i].tasks.push( std::move(task) ); // Notify the thread that there is work do to... threads[i].cv.notify_one(); } // Wait for all the tasks to be completed... for( auto& f : futures ) f.wait(); futures.clear(); } inline ~MyThreadPool() { // Send stop signal to all threads and join them... for( int i=0; i<nThreads; ++i ) { std::unique_lock<std::mutex> l( threads[i].m ); threads[i].stop = true; threads[i].cv.notify_one(); } // Join all the threads for( int i=0; i<nThreads; ++i ) threads[i].t.join(); delete[] threads; } }; #endif //__THREADPOOL_H__
3,370
C++
.h
99
25.838384
116
0.516507
ASTex-ICube/semiproctex
39
8
2
LGPL-2.1
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,949
hvBitmap.h
ASTex-ICube_semiproctex/Semiproc_synthesis_Src/3rdParty/Externals/hview/hvBitmap.h
/* * Code author: Jean-Michel Dischler */ /** * @version 1.0 */ #if !defined(AFX_BITMAP_H__098453F0_1C38_49E9_A6F4_AABF90AA55E8__INCLUDED_) #define AFX_BITMAP_H__098453F0_1C38_49E9_A6F4_AABF90AA55E8__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include <vector> #include <math.h> #include "hvBoolArray2.h" #include "hvVec2.h" namespace hview { template <class T> class hvPict ; //////////////////////////////////////////////////////////// class hvBitmap : public hvBoolArray2 //////////////////////////////////////////////////////////// { public: enum operation { LESS, LEQUAL, EQUAL, GEQUAL, GREATER, NOTEQUAL }; hvBitmap(): hvBoolArray2() { } hvBitmap(int x, int y, bool nil): hvBoolArray2(x,y,nil) { } template <class T, class U> hvBitmap(const hvPict<T> &p, hvBitmap::operation op, U value); template <class T, class U> void convert(const hvPict<T> &p, hvBitmap::operation op, U value); template <class T, class U> void convert(const hvPict<T> &p, hvBitmap::operation op, int nn, U value[]); void operator~() { hvBoolArray2::operator ~(); } void operator|=(const hvBitmap &x) { hvBoolArray2::operator|=(x); } void operator&=(const hvBitmap &x) { hvBoolArray2::operator&=(x); } void operator^=(const hvBitmap &x) { hvBoolArray2::operator^=(x); } void operatorOr(int x, int y, int px, int py, int dx, int dy, const hvBitmap &bb) { int i,j; for (i=0; i<dx; i++) for (j=0; j<dy; j++) { if (x+i>=0 && x+i<sizeX() && y+j>=0 && y+j<sizeY()) { set(x+i,y+j,get(x+i,y+j)||bb.get(px+i,py+j)); } } } int count() const { int i,j, c=0; for (i=0; i<sizeX(); i++) for (j=0; j<sizeY(); j++) if (get(i,j)) c++; return c; } int count(int px, int py, int sx, int sy) const { int i,j, c=0; for (i=px; i<=sx; i++) for (j=py; j<=sy; j++) if (get(i,j)) c++; return c; } void bary(int &x, int &y) const { int i,j, c=0; x=0; y=0; for (i=0; i<sizeX(); i++) for (j=0; j<sizeY(); j++) if (get(i,j)) { x+=i; y+=j; c++; } x /= c; y/=c; } void shrink(const hvBitmap &bm, bool def) { reset(bm.sizeX()/2, bm.sizeY()/2, false); for (int i=0; i<sizeX(); i++) for (int j=0; j<sizeY(); j++) { int sum=bm.get(2*i,2*j)?1:0; sum += bm.get(2*i+1,2*j)?1:0; sum += bm.get(2*i,2*j+1)?1:0; sum += bm.get(2*i+1,2*j+1)?1:0; bool v=def; if (sum==0) v=false; else if (sum==4) v=true; set(i,j,v); } } void shrink(const hvBitmap &bm) { reset(bm.sizeX()/2, bm.sizeY()/2, false); for (int i=0; i<sizeX(); i++) for (int j=0; j<sizeY(); j++) { int sum=bm.get(2*i,2*j)?1:0; sum += bm.get(2*i+1,2*j)?1:0; sum += bm.get(2*i,2*j+1)?1:0; sum += bm.get(2*i+1,2*j+1)?1:0; bool v; if (sum>2) v=true; else v=false; set(i,j,v); } } void rescalex(const hvBitmap &bm, float scx) { reset((int)((float)bm.sizeX()*scx) , bm.sizeY() , false); for (int i = 0; i<this->sizeX(); i++) for (int j = 0; j<this->sizeY(); j++) { int x = (int)((float)i / scx); if (x >= bm.sizeX()) x = bm.sizeX() - 1; set(i, j, bm.get(x, j)); } } void rotation(const hvBitmap &bm, float angle) { int i, j, ii, jj; int dx = bm.sizeX() / 2, dy = bm.sizeY() / 2; int sx = 0, sy = 0; for (ii = 0; ii <= 1; ii++) for (jj = 0; jj <= 1; jj++) { int rx = (int)((float)(ii==0?dx:-dx)*cos(angle) - (float)(jj==0?dy:-dy)*sin(angle)); int ry = (int)((float)(ii==0?dx:-dx)*sin(angle) + (float)(jj==0?dy:-dy)*cos(angle)); if (rx > sx) sx = rx; if (ry > sy) sy = ry; } bool cont = true; for (i = 1; i <= (sx < sy ? sx:sy) && cont; i++) { bool valid = true; for (j = -i; j <= i && valid; j++) { int xx = bm.sizeX() / 2 + (int)((float)j*cos(-angle) - (float)i*sin(-angle)); int yy = bm.sizeY() / 2 + (int)((float)j*sin(-angle) + (float)i*cos(-angle)); if (xx < 0 || xx >= bm.sizeX() || yy < 0 || yy >= bm.sizeY()) valid = false; xx = bm.sizeX() / 2 + (int)((float)j*cos(-angle) + (float)i*sin(-angle)); yy = bm.sizeY() / 2 + (int)((float)j*sin(-angle) - (float)i*cos(-angle)); if (xx < 0 || xx >= bm.sizeX() || yy < 0 || yy >= bm.sizeY()) valid = false; xx = bm.sizeX() / 2 + (int)((float)i*cos(-angle) - (float)j*sin(-angle)); yy = bm.sizeY() / 2 + (int)((float)i*sin(-angle) + (float)j*cos(-angle)); if (xx < 0 || xx >= bm.sizeX() || yy < 0 || yy >= bm.sizeY()) valid = false; xx = bm.sizeX() / 2 + (int)(-(float)i*cos(-angle) - (float)j*sin(-angle)); yy = bm.sizeY() / 2 + (int)(-(float)i*sin(-angle) + (float)j*cos(-angle)); if (xx < 0 || xx >= bm.sizeX() || yy < 0 || yy >= bm.sizeY()) valid = false; } if (!valid) cont = false; } int resol = i - 1; this->reset(2*resol+1, 2*resol+1, false); for (int i = -resol; i<=resol; i++) for (int j = -resol; j<=resol; j++) { int xx = bm.sizeX() / 2 + (int)((float)i*cos(-angle) - (float)j*sin(-angle)); int yy = bm.sizeY() / 2 + (int)((float)i*sin(-angle) + (float)j*cos(-angle)); if (xx >= 0 && xx < bm.sizeX() && yy >= 0 && yy < bm.sizeY()) { this->set(i+resol, j+resol, bm.get(xx, yy)); } } } void seedfill(int x, int y) { if (x<0 || y<0 || x>=sizeX() || y>=sizeY()) return; if (get(x,y)) return; set(x,y,true); int i,a,b; for (i=x+1; i<sizeX() && !get(i,y); i++) set(i,y, true); b=i-1; for (i=x-1; i>=0 && !get(i,y); i--) set(i,y, true); a = i+1; for (i=a; i<=b; i++) { seedfill(i,y-1); seedfill(i,y+1); } } void seedfill(int x, int y, hvBitmap &bm) { if (x<0 || y<0 || x>=sizeX() || y>=sizeY()) return; if (get(x,y)) return; set(x,y,true); bm.set(x,y,true); int i,a,b; for (i=x+1; i<sizeX() && !get(i,y); i++) { set(i,y, true); bm.set(i,y, true); } b = i - 1; if (b >= sizeX()) b = sizeX() - 1; for (i=x-1; i>=0 && !get(i,y); i--) { set(i,y, true); bm.set(i,y, true); } a = i + 1; if (a < 0) a = 0; for (i=a; i<=b; i++) { if (y>=1) if (!get(i,y-1)) seedfill(i,y-1,bm); if (y<=sizeY()-2) if (!get(i,y+1)) seedfill(i,y+1,bm); } } void seedfill(int x, int y, hvBitmap &bm, hvVec2<int> &min, hvVec2<int> &max ) { if (x<0 || y<0 || x>=sizeX() || y>=sizeY()) return; if (get(x,y)) return; set(x,y,true); bm.set(x,y,true); min.keepMin(min,hvVec2<int>(x,y)); max.keepMax(max,hvVec2<int>(x,y)); int i,a,b; for (i=x+1; i<sizeX() && !get(i,y); i++) { set(i,y, true); bm.set(i,y, true); min.keepMin(min,hvVec2<int>(i,y)); max.keepMax(max,hvVec2<int>(i,y)); } b=i-1; for (i=x-1; i>=0 && !get(i,y); i--) { set(i,y, true); bm.set(i,y, true); min.keepMin(min,hvVec2<int>(i,y)); max.keepMax(max,hvVec2<int>(i,y)); } a = i+1; for (i=a; i<=b; i++) { this->seedfill(i,y-1,bm,min,max); this->seedfill(i,y+1,bm,min,max); } } bool seedfillCorners(int x, int y, hvBitmap &bml, hvBitmap &bmr, hvBitmap &bmb, hvBitmap &bmt, int qq, int &mx, int &my) { if (get(x,y)) return true; set(x,y,true); //printf("(%d,%d):%d\n",x,y,qq); if(qq==3) { bml.set(x,y,true); mx+=x+this->sizeX(); my+=y+this->sizeY(); } else if (qq==2) { bmr.set(x,y,true); mx+=x; my+=y+this->sizeY(); } else if (qq==1) { bmb.set(x,y,true); mx+=x+this->sizeX(); my+=y; } else { bmt.set(x,y,true); mx+=x; my+=y; } int i,a,b; for (i=x+1; i<sizeX() && !get(i,y); i++) { set(i,y, true); if(qq==3) { bml.set(i,y,true); mx+=i+this->sizeX(); my+=y+this->sizeY(); } else if (qq==2) { bmr.set(i,y,true); mx+=i; my+=y+this->sizeY(); } else if (qq==1) { bmb.set(i,y,true); mx+=i+this->sizeX(); my+=y; } else { bmt.set(i,y,true); mx+=i; my+=y; } } b=i-1; if (b==sizeX()-1) { if (qq==2) { if (!this->seedfillCorners(0,y,bml,bmr,bmb,bmt,3,mx,my)) return false; } else if (qq==0) { if (!this->seedfillCorners(0,y,bml,bmr,bmb,bmt,1,mx,my)) return false; } else { std::cout<<"component over two borders b (q="<<qq<<"\n"; return false; } } for (i=x-1; i>=0 && !get(i,y); i--) { set(i,y, true); if(qq==3) { bml.set(i,y,true); mx+=i+this->sizeX(); my+=y+this->sizeY(); } else if (qq==2) { bmr.set(i,y,true); mx+=i; my+=y+this->sizeY(); } else if (qq==1) { bmb.set(i,y,true); mx+=i+this->sizeX(); my+=y; } else { bmt.set(i,y,true); mx+=i; my+=y; } } a = i+1; if (a==0) { if (qq==3) { if (!this->seedfillCorners(sizeX()-1,y,bml,bmr,bmb,bmt,2,mx,my)) return false; } else if (qq==1) { if (!this->seedfillCorners(sizeX()-1,y,bml,bmr,bmb,bmt,0,mx,my)) return false; } else { std::cout << "component over two borders b (q=" << qq << ")\n"; return false; } } for (i=a; i<=b; i++) { if (y>0) { if (!this->seedfillCorners(i,y-1,bml, bmr, bmb, bmt,qq, mx, my)) return false; } else { if (qq==3) { if (!this->seedfillCorners(i,sizeY()-1,bml, bmr, bmb, bmt, 1, mx, my)) return false; } else if (qq==2) { if (! this->seedfillCorners(i,sizeY()-1,bml, bmr, bmb, bmt, 0, mx, my)) return false; } else { std::cout<<"component over two borders bottom (q="<<qq<<", y="<<y<<")\n"; return false; } } if (y<sizeY()-1) { if (!this->seedfillCorners(i,y+1,bml,bmr,bmb,bmt,qq,mx,my)) return false; } else { if (qq==1) { if (!this->seedfillCorners(i,0,bml, bmr, bmb, bmt, 3, mx, my)) return false; } else if (qq==0) { if (!this->seedfillCorners(i,0,bml, bmr, bmb, bmt, 2, mx, my)) return false; } else { std::cout << "component over two borders top (q=" << qq << ", y=" << y<<")\n"; return false; } } } return true; } void extract(std::vector<hvVec2<int> > &ll, int step=100) { int i,j; for (i=0; i<sizeX(); i++) for (j=0; j<sizeY(); j++) { if (get(i,j)) { if (ll.size()==ll.capacity()) ll.resize(ll.size()+step); ll.push_back(hvVec2<int>(i,j)); } } } bool extractCC(hvBitmap &bm) { int i,j; bm.reset(sizeX(),sizeY(), false); for (i=0; i<sizeX(); i++) for (j=0; j<sizeY(); j++) { if (get(i,j)) { hvBitmap bb; bb=*this; ~bb; bb.seedfill(i,j,bm); return true; } } return false; } void mirror() { int i,j; for (i=0; i<sizeX(); i++) for (j=0; j<sizeY(); j++) { if (get(i,j)) { if (sizeX()-i>0 && sizeX()-i<sizeX() && sizeY()-j>0 && sizeY()-j<sizeY()) set(sizeX()-i,sizeY()-j,true); } } } int extractCC(std::vector<hvBitmap *> &ll) { int num=0; hvBitmap bm; bm = *this; while (bm.count()>0) { hvBitmap *ccmask; int i,j; ccmask = new hvBitmap(sizeX(),sizeY(), false); bool cont=true; for (i=0; i<sizeX() && cont; i++) for (j=0; j<sizeY() && cont; j++) { if (bm.get(i,j)) { ~bm; bm.seedfill(i,j,*ccmask); ~bm; ll.push_back(ccmask); num++; cont=false; } } } return num; } void holes() { int i; for (i=0; i<sizeX(); i++) seedfill(i,0); for (i=0; i<sizeX(); i++) seedfill(i,sizeY()-1); for (i=0; i<sizeY(); i++) seedfill(0,i); for (i=0; i<sizeY(); i++) seedfill(sizeX()-1,i); operator~(); } void fillholes() { hvBitmap bm; bm = *this; bm.holes(); operator|=(bm); } void holesw() { operator~(); int i; for (i = 0; i<sizeX(); i++) seedfill(i, 0); for (i = 0; i<sizeX(); i++) seedfill(i, sizeY() - 1); for (i = 0; i<sizeY(); i++) seedfill(0, i); for (i = 0; i<sizeY(); i++) seedfill(sizeX(), i); } void fillholesw() { hvBitmap bm; bm = *this; bm.holesw(); operator|=(bm); } // standard filter orperators void median(int kernelsx, int kernelsy) { hvBitmap bm; bm = *this; median(bm, kernelsx, kernelsy); } void median(const hvBoolArray2 &x, int kernelsx, int kernelsy) { int ksx = kernelsx/2, ksy = kernelsy/2; int i, j, ii, jj, npos, nneg; reset(x.sizeX(),x.sizeY(), false); for (i=0; i<x.sizeX(); i++) for (j=0; j<x.sizeY(); j++) { npos=0; nneg=0; for (ii=-ksx; ii<=ksx; ii++) for (jj=-ksy; jj<=ksy; jj++) { if (i+ii>=0 && i+ii<x.sizeX() && j+jj>=0 && j+jj<x.sizeY()) { if (x.get(i+ii,j+jj)) npos++; else nneg++; } } if (npos>=nneg) set(i,j, true); else set(i,j, false); } } void dilatation(int kernelsx, int kernelsy) { hvBitmap bm; bm = *this; dilatation(bm, kernelsx, kernelsy); } void dilatation(const hvBoolArray2 &x, int kernelsx, int kernelsy) { int ksx = kernelsx/2, ksy = kernelsy/2; int i, j, ii, jj, npos, nneg; reset(x.sizeX(),x.sizeY(), false); for (i=0; i<x.sizeX(); i++) for (j=0; j<x.sizeY(); j++) { npos=0; nneg=0; for (ii=-ksx; ii<=ksx; ii++) for (jj=-ksy; jj<=ksy; jj++) { if (sqrt((double)(ii*ii)+(double)(jj*jj))<=(ksx+ksy)/2) if (i+ii>=0 && i+ii<x.sizeX() && j+jj>=0 && j+jj<x.sizeY()) { if (x.get(i+ii,j+jj)) npos++; else nneg++; } } if (npos>=1) set(i,j,true); else set(i,j,false); } } void erosion(int kernelsx, int kernelsy) { hvBitmap bm; bm = *this; erosion(bm, kernelsx, kernelsy); } void erosion(const hvBoolArray2 &x, int kernelsx, int kernelsy) { int ksx = kernelsx/2, ksy = kernelsy/2; int i, j, ii, jj, npos, nneg; reset(x.sizeX(),x.sizeY(), false); for (i=0; i<x.sizeX(); i++) for (j=0; j<x.sizeY(); j++) { npos=0; nneg=0; for (ii=-ksx; ii<=ksx; ii++) for (jj=-ksy; jj<=ksy; jj++) { if (i+ii>=0 && i+ii<x.sizeX() && j+jj>=0 && j+jj<x.sizeY()) { if (x.get(i+ii,j+jj)) npos++; else nneg++; } else nneg++; } if (nneg>=1) set(i,j,false); else set(i,j,true); } } void erosionTorus(const hvBoolArray2 &x, int kernelsx, int kernelsy) { int ksx = kernelsx/2, ksy = kernelsy/2; int i, j, ii, jj, npos, nneg; reset(x.sizeX(),x.sizeY(), false); for (i=0; i<x.sizeX(); i++) for (j=0; j<x.sizeY(); j++) { npos=0; nneg=0; for (ii=-ksx; ii<=ksx; ii++) for (jj=-ksy; jj<=ksy; jj++) { int xx=i+ii; if (xx<0) xx+=x.sizeX(); else if (xx>=x.sizeX()) xx-=x.sizeX(); int yy=j+jj; if (yy<0) yy+=x.sizeY(); else if (yy>=x.sizeY()) yy-=x.sizeY(); if (x.get(xx,yy)) npos++; else nneg++; } if (nneg>=1) set(i,j,false); else set(i,j,true); } } void erosionTorus(const hvBoolArray2 &x, int kernelsx, int kernelsy, int minx, int miny, int maxx, int maxy) { int ksx = kernelsx/2, ksy = kernelsy/2; int i, j, ii, jj, npos, nneg; reset(x.sizeX(),x.sizeY(), false); for (i=minx; i<=maxx; i++) for (j=miny; j<=maxy; j++) { npos=0; nneg=0; for (ii=-ksx; ii<=ksx; ii++) for (jj=-ksy; jj<=ksy; jj++) { int xx=i+ii; if (xx<0) xx+=x.sizeX(); else if (xx>=x.sizeX()) xx-=x.sizeX(); int yy=j+jj; if (yy<0) yy+=x.sizeY(); else if (yy>=x.sizeY()) yy-=x.sizeY(); if (x.get(xx,yy)) npos++; else nneg++; } if (nneg>=1) set(i,j,false); else set(i,j,true); } } void erosion(const hvBoolArray2 &x, int kernelsx, int kernelsy, int startx, int starty, int endx, int endy) { int ksx = kernelsx/2, ksy = kernelsy/2; int i, j, ii, jj, npos, nneg; reset(x.sizeX(),x.sizeY(), false); for (i=startx; i<=endx; i++) for (j=starty; j<=endy; j++) { npos=0; nneg=0; for (ii=-ksx; ii<=ksx; ii++) for (jj=-ksy; jj<=ksy; jj++) { if (i+ii>=0 && i+ii<x.sizeX() && j+jj>=0 && j+jj<x.sizeY()) { if (x.get(i+ii,j+jj)) npos++; else nneg++; } } if (i>=0 && i<x.sizeX() && j>=0 && j<x.sizeY()) if (nneg>=1) set(i,j,false); else set(i,j,true); } } bool thinning() { hvBitmap bm; bm=*this; thinning(bm); } bool thinning(const hvBitmap &pi) { int i,j; hvBitmap pres; pres=pi; bool modif; int nnul; modif=false; *this = pres; for (i=1; i<pi.sizeX()-1; i++) for (j=1; j<pi.sizeY()-1; j++) { if ( pres.get(i,j) ) { nnul=0; for (int ii=0; ii<=2; ii++) for (int jj=0; jj<=2; jj++) if (pres.get(i+ii-1,j+jj-1)) { nnul++; } if (nnul>2 && nnul!=9) { if ( ( !pres.get(i-1,j-1) && !pres.get(i,j-1) && !pres.get(i+1,j-1) && pres.get(i-1,j+1) && pres.get(i,j+1) && pres.get(i+1,j+1) ) || ( !pres.get(i,j-1) && !pres.get(i+1,j-1) && pres.get(i-1,j) && !pres.get(i+1,j) && pres.get(i,j+1) ) || ( !pres.get(i-1,j-1) && pres.get(i+1,j-1) && !pres.get(i-1,j) && pres.get(i+1,j) && !pres.get(i-1,j+1) && pres.get(i+1,j+1) ) || ( !pres.get(i-1,j-1) && !pres.get(i,j-1) && !pres.get(i-1,j) && pres.get(i+1,j) && pres.get(i,j+1) ) || ( pres.get(i-1,j-1) && pres.get(i,j-1) && pres.get(i+1,j-1) && !pres.get(i-1,j+1) && !pres.get(i,j+1) && !pres.get(i+1,j+1) ) || ( pres.get(i,j-1) && !pres.get(i-1,j) && pres.get(i+1,j) && !pres.get(i-1,j+1) && !pres.get(i,j+1) ) || ( pres.get(i-1,j-1) && !pres.get(i+1,j-1) && pres.get(i-1,j) && !pres.get(i+1,j) && pres.get(i-1,j+1) && !pres.get(i+1,j+1) ) || ( pres.get(i,j-1) && pres.get(i-1,j) && !pres.get(i+1,j) && !pres.get(i,j+1) && !pres.get(i+1,j+1) ) ) { set(i,j, false); modif=true; } else set(i,j, true); } else set(i,j, true); } else set(i,j, false); } return modif; } void skeleton(const hvBitmap &pi) { hvBitmap pres=pi; bool modif = true; do { if (thinning(pres)) pres = *this; else modif=false; } while(modif); } // drawing shapes void bresenham(int spx, int spy, int epx, int epy, bool val) { int i, dx, dy, delta=0, px=0, py=0; if (spx>epx) { i=spx; spx=epx; epx=i; i=spy; spy=epy; epy=i; } dx = epx-spx; dy = epy-spy; if (dx>=(dy>0?dy:-dy)) { if (dy>=0) { for (i=0; i<dx; i++) { if (delta<dx-dy) delta += dy; else { delta += (-dx+dy); py++; } set(spx+i,spy+py, val); } } else { dy = -dy; for (i=0; i<dx; i++) { if (delta<dx-dy) delta += dy; else { delta += (-dx+dy); py--; } set(spx+i,spy+py, val); } } } else { if (dy>=0) { for (i=0; i<dy; i++) { if (delta<dy-dx) delta += dx; else { delta += (-dy+dx); px++; } set(spx+px,spy+i, val); } } else { dy = -dy; for (i=0; i<dy; i++) { if (delta<dy-dx) delta += dx; else { delta += (-dy+dx); px++; } set(spx+px,spy-i, val); } } } } void drawRect(int spx, int spy, int dx, int dy, bool val) { int i,j; for (i=spx; i<spx+dx; i++) for (j=spy; j<spy+dy; j++) { set(i,j,val); } } void drawPolygon(const std::vector<hvVec2<int> > &vert, bool val=true) { hvVec2<int> vvs, vve; hvBitmap pres(sizeX(), sizeY(), false); int i; for (i=0; i<(int)vert.size();i++) { vvs = vert.at(i); if (i+1==vert.size()) vve=vert.at(0); else vve = vert.at(i+1); pres.bresenham(vvs.X(), vvs.Y(), vve.X(), vve.Y(), true); } pres.fillholes(); if (val) operator|=(pres); else { ~pres; operator&=(pres); } } void drawEllipse(int x, int y, int rx, int ry, double alpha, bool val=true) { double i,j; bool cont; for (i=0.0; i<=(double)rx; i+=0.5) { cont=true; for (j=0.0; j<=(double)ry && cont; j+=0.5) { double vv; if (rx!=0 && ry!=0) vv = i*i/(double)(rx*rx)+j*j/(double)(ry*ry); else if (rx==0) vv = j*j/(double)(ry*ry); else vv = i*i/(double)(rx*rx); if (vv <= 1.0) { int a = x+(int)(i*cos(alpha)-j*sin(alpha)); int b = y+(int)(i*sin(alpha)+j*cos(alpha)); if (a>=0 && a<sizeX() && b>=0 && b<sizeY()) set(a, b, val); a = x+(int)(-i*cos(alpha)-j*sin(alpha)); b = y+(int)(-i*sin(alpha)+j*cos(alpha)); if (a>=0 && a<sizeX() && b>=0 && b<sizeY()) set(a, b, val); a = x+(int)(-i*cos(alpha)+j*sin(alpha)); b = y+(int)(-i*sin(alpha)-j*cos(alpha)); if (a>=0 && a<sizeX() && b>=0 && b<sizeY()) set(a, b, val); a = x+(int)(i*cos(alpha)+j*sin(alpha)); b = y+(int)(i*sin(alpha)-j*cos(alpha)); if (a>=0 && a<sizeX() && b>=0 && b<sizeY()) set(a, b, val); } else cont=false; } } } // analysis and information extraction void extractBoxes(std::vector<hvVec2<int> > &blist, int sx, int sy) const { int i,j,ii,jj; for (i=0; i<this->sizeX()-sx; i+=2) for (j=0; j<this->sizeY()-sy; j+=2) { if (this->get(i,j)) { bool cont=true; for (ii=i; ii<i+sx && cont; ii++) for (jj=j; jj<j+sy && cont; jj++) { if (!this->get(ii,jj)) cont=false; } blist.push_back(hvVec2<int>(i,j)); } } } void box(hvVec2<int> &min, hvVec2<int> &max) const { min = hvVec2<int>(sizeX(), sizeY()); max = hvVec2<int>(0,0); int i,j; for (i=0; i<sizeX(); i++) for (j=0; j<sizeY(); j++) { if (get(i,j)) { hvVec2<int> vv(i,j); min.keepMin(min, vv); max.keepMax(max, vv); } } } void findMainAxis(int cx, int cy, double &alpha, int &dist) { int i,j; dist=0; for (i=0; i<sizeX(); i++) for (j=0; j<sizeY(); j++) { double dd = sqrt((double)((i-cx)*(i-cx)+(j-cy)*(j-cy))); if (get(i,j) && (int)dd>dist) { if (i==cx) alpha=M_PI/2.0; else alpha = atan((double)(j-cy)/(double)(i-cx)); dist=(int)dd; } } } int findBestMatchingEllipse(int cx, int cy, int &rx, int &ry, double &alpha) { int i,j, rad, nn, pas; double aa, amoy; int count = sizeX()*sizeY(); findMainAxis(cx, cy, amoy, rad); if (amoy==0.0) { nn=0; pas=0; } else { nn = (int)(M_PI/amoy); pas = 32/nn; } //printf("main axis=%g at %d, nn=%d, pas=%d\n",amoy,rad,nn,pas); //for (aa=(double)(pas-2)*M_PI/32.0; aa<=(double)(pas+2)*M_PI/32.0; aa+=M_PI/32.0) //for (i=rad-5; i<rad+5; i++) aa = amoy; i=rad; for (j=i/5; j<=i; j++) { if (i>=1) { hvBitmap be(sizeX(), sizeY(), false); be.drawEllipse(cx, cy, i,j, aa); be ^= *this; int cc = be.count(); if (cc<count) { rx=i; ry=j; alpha=aa; count = cc; } } } //printf("Main ellipse: %d,%d, a=%g, count=%d\n",rx,ry,alpha, count); return count; } int findBestMatchingEllipseRing(int cx, int cy, int &rx, int &ry, double &alpha, double &ratio) { int k; int count; double rr; count=findBestMatchingEllipse(cx,cy,rx,ry,alpha); ratio=0.0; for (k=1; k<rx-1; k++) { rr = (double)k/(double)rx; hvBitmap be(sizeX(), sizeY(), false); be.drawEllipse(cx, cy, rx,ry, alpha); be.drawEllipse(cx, cy, (int)((double)rx*rr),(int)((double)ry*rr), alpha, false); be ^= *this; int cc = be.count(); if (cc<count) { ratio=rr; count = cc; } } return count; } // other operations // standard filter orperators /* void noiseDistortion(const hvBitmap &bm, double fx, double fy, int dx, int dy) { *this = bm; int i,j; for (i=0; i<sizeX(); i++) for (j=0; j<sizeY(); j++) { int px = i+(int)((double)dx*hvNoise::gnoise((double)i*(double)fx+23.987, (double)j*(double)fy-6.3327, 42.12345)); int py = j+(int)((double)dy*hvNoise::gnoise((double)i*(double)fx-13.987, (double)j*(double)fy+36.3427, -22.345)); if (px<0) px=0; else if (px>=sizeX()) px=sizeX()-1; if (py<0) py=0; else if (py>=sizeY()) py=sizeY()-1; set(i,j,bm.get(px,py)); } } */ void randomPosition(bool state, hvVec2<int> &pos) const { int px, py; int count=0; do { count++; px=(int)((double)rand()/(double)RAND_MAX*(double)sizeX()); if (px>=sizeX()) px=sizeX()-1; py=(int)((double)rand()/(double)RAND_MAX*(double)sizeY()); if (py>=sizeY()) py=sizeY()-1; if (get(px,py)==state) { pos=hvVec2<int>(px,py); return; } } while (count<20); int i,j; for (j=py; j<sizeY(); j++) for (i=px; i<sizeX(); i++) if (get(i,j)==state) { pos=hvVec2<int>(i,j); return; } for (j=py; j<sizeY(); j++) for (i=px; i>=0; i--) if (get(i,j)==state) { pos=hvVec2<int>(i,j); return; } for (j=py; j>=0; j--) for (i=px; i<sizeX(); i++) if (get(i,j)==state) { pos=hvVec2<int>(i,j); return; } for (j=py; j>=0; j--) for (i=px; i>=0; i--) if (get(i,j)==state) { pos=hvVec2<int>(i,j); return; } hvFatal("no position possible in randomPosition"); } }; } #endif // !efined(AFX_BITMAP_H__098453F0_1C38_49E9_A6F4_AABF90AA55E8__INCLUDED_)
23,535
C++
.h
772
26.873057
151
0.540223
ASTex-ICube/semiproctex
39
8
2
LGPL-2.1
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,950
hvLinearTransform3.h
ASTex-ICube_semiproctex/Semiproc_synthesis_Src/3rdParty/Externals/hview/hvLinearTransform3.h
/* * Code author: Jean-Michel Dischler */ /** * @version 1.0 */ // LinearTransform3.h: interface for the LinearTransform3 class. // // Define a linear transform in 3D space (scaling, translation, rotation, projection, etc.) // // LinearTransform3 derives from matrix 4x4 (homogenous coordinates) // A main operation consists in applying the transform to 3D points // // By JMD 10/8/06 ////////////////////////////////////////////////////////////////////// #if !defined(AFX_LINEARTRANSFORM3_H__33F894B9_F2FB_4902_97D2_D69639938055__INCLUDED_) #define AFX_LINEARTRANSFORM3_H__33F894B9_F2FB_4902_97D2_D69639938055__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include "hvFrame3.h" #include "hviTransform.h" namespace hview { template <class T> class hvLinearTransform3 : public hvMat4<T>, public hviTransform<hvLinearTransform3<T>, hvVec3<T> > { public: // constructor: defines identity transform hvLinearTransform3<T>() { } //template <class X> hvLinearTransform3<T>(const hvLinearTransform3<X> &v) { i = T(v.I()); j=T(v.J()); k=T(v.K()); l=T(v.L()); } template <class X> void cast(const hvLinearTransform3<X> &v) { hvMat4<T>::i.template cast<X>(v.I()); hvMat4<T>::j. template cast<X>(v.J()); hvMat4<T>::k.template cast<X>(v.K()); hvMat4<T>::l.template cast<X>(v.L()); } hvLinearTransform3<T>(const hvFrame3<T> &fr) { hvVec3<T> v=fr.origin(); this->setIdentity(); this->translation(v); this->frame(fr.I(), fr.J(), fr.K()); } void inverseFrame3(const hvFrame3<T> &fr) { hvVec3<T> v=fr.origin(); v.reverse(); this->setIdentity(); this->inverseframe(fr.I(), fr.J(), fr.K()); this->translation(v); } void setIdentity() { hvMat4<T>::i=hvVec4<T>(1,0,0,0); hvMat4<T>::j=hvVec4<T>(0,1,0,0); hvMat4<T>::k=hvVec4<T>(0,0,1,0); hvMat4<T>::l=hvVec4<T>(0,0,0,1); } // List of transforms: each is composed with the current one // shift of vector v void translation(const hvVec3<T> &v) { hvMat4<T> m(hvMat3<T>(), v); this->mult(*this, m); } // scale the three components by factors given by v void scale(const hvVec3<T> &v) { hvMat4<T> m(v); this->mult(*this, m); } // rotation along X axis by angle a in radiant void rotX(T a) { hvMat4<T> m( hvVec4<T>(1.0, 0.0, 0.0, 0.0), hvVec4<T>(0.0, cos(a), sin(a), 0.0), hvVec4<T>(0.0, -sin(a), cos(a), 0.0), hvVec4<T>(0.0, 0.0, 0.0, 1.0) ); this->mult(*this, m); } // rotation along Y axis by angle a in radiant void rotY(T a) { hvMat4<T> m( hvVec4<T>(cos(a),0.0,-sin(a),0), hvVec4<T>(0.0, 1.0, 0.0, 0.0), hvVec4<T>(sin(a), 0.0, cos(a), 0.0), hvVec4<T>(0.0, 0.0, 0.0, 1.0) ); this->mult(*this, m); } // rotation along Z axis by angle a in radiant void rotZ(T a) { hvMat4<T> m( hvVec4<T>(cos(a), sin(a), 0.0, 0.0), hvVec4<T>(-sin(a), cos(a), 0.0, 0.0), hvVec4<T>(0.0, 0.0, 1.0, 0.0), hvVec4<T>(0.0, 0.0, 0.0, 1.0) ); this->mult(*this, m); } // rotation along axis v by angle a in radiant // v must be normalized void rotation(const hvVec3<T> &v, T a) { hvMat3<T> m(v); hvMat3<T> s ( hvVec3<T>(0.0, v.Z(), -v.Y()), hvVec3<T>(-v.Z(), 0.0, v.X()), hvVec3<T>(v.Y(), -v.X(), 0.0) ); s.scale(sin(a)); hvMat3<T> t; hvMat3<T> n; n.sub(t,m); n.scale(cos(a)); t.add(m, n); t.add(t, s); hvMat4<T> res(t); this->mult(*this, res); } // defines perspective projection: (l,b) resp. (r,t) define the bottom-left resp. // top-right corners, n and f define the near / far clipping planes // NOTE: n<f, l<r, b<t, n>0, f>0 // result of Apply is vec3 with x,y,z normalized between -1 and 1 if inside frustum // z represents the distance from eye, z>1 means farther than far plan, // z<-1 means closer or behind near plane, z=-INF means on eye plane // use only Apply for vector with z<0 void frustum(T l, T r, T b, T t, T n, T f) { hvMat4<T> res( hvVec4<T>(2.0*n/(r-l), 0.0, 0.0, 0.0), hvVec4<T>(0.0, 2.0*n/(t-b), 0.0, 0.0), hvVec4<T>((r+l)/(r-l), (t+b)/(t-b), -(f+n)/(f-n), -1.0), hvVec4<T>(0.0, 0.0, -2.0*f*n/(f-n), 0.0) ); this->mult(*this, res); } // defines orthographic projection: (l,b) resp. (r,t) define the bottom-left resp. // top-right corners, n and f define the near / far clipping planes // NOTE: n<f, l<r, b<t, n>0, f>0 // result of Apply is vec3 with x,y,z normalized between -1 and 1 if inside frustum // z represents the distance from eye plane, z>1 means farther than far plane, // z<-1 means closer or behind near plane // use only Apply for vector with z<0 void ortho(T l, T r, T b, T t, T n, T f) { hvMat4<T> res( hvVec4<T>(2.0/(r-l), 0.0, 0.0, 0.0), hvVec4<T>(0.0, 2.0/(t-b), 0.0, 0.0), hvVec4<T>(0.0, 0.0, -2.0/(f-n), 0.0), hvVec4<T>(-(r+l)/(r-l), -(t+b)/(t-b), -(f+n)/(f-n), 1.0) ); this->mult(*this, res); } // defines a change of vector frame given by: // vi,vj,vk -> new frame // NOTE: vi,vj,vk must be orthogonal vectors void frame(const hvVec3<T> &vi, const hvVec3<T> &vj, const hvVec3<T> &vk) { hvMat3<T> mat(vi,vj,vk); mat.inverse(); hvMat4<T> m1(mat); this->mult(*this, m1); } // defines a change of vector frame given by: // new frame -> vi,vj,vk // NOTE: vi,vj,vk must be orthogonal vectors void inverseframe(const hvVec3<T> &vi, const hvVec3<T> &vj, const hvVec3<T> &vk) { hvMat3<T> mat(vi,vj,vk); hvMat4<T> m1(mat); this->mult(*this, m1); } // defines a change of frame given by: // eye -> eye position // at -> focus point // up -> up vector to define a full local frame on eye // vector(at, eye) defines Z axis, up defines Y axis, and X axis is computed // from cross product // NOTE: up must be normalized and perpendicular to vector(at, eye), and at /= eye void lookAt(const hvVec3<T> &eye, const hvVec3<T> &at, const hvVec3<T> &up) { hvVec3<T> zaxis; zaxis.PVec(eye, at); zaxis.normalize(zaxis.norm()); hvVec3<T> xaxis; xaxis.cross(up, zaxis); xaxis.normalize(xaxis.norm()); zaxis.reverse(); hvVec3<T> io=eye; io.reverse(); hvMat4<T> m1(hvMat3<T>(), io); hvMat3<T> ba( xaxis, up, zaxis); hvMat3<T> r; r.inverse(ba, ba.det()); hvMat4<T> m2(r); this->mult(*this, m2); this->mult(*this, m1); } // compose two transforms with each other void compose(const hvLinearTransform3<T> &a, const hvLinearTransform3<T> &b) { this->mult(a,b); } // compose two transforms with each other void compose(const hvLinearTransform3<T> &a) { this->operator*=(a); } // apply a transform to a 3D point, result is a 3D point hvVec3<T> apply(const hvVec3<T> &v) const { hvVec4<T> u(v); //printf("in apply transform3: %g,%g,%g,%g\n", u.X(),u.Y(),u.Z(),u.W()); hvVec4<T> res=this->mult(u); //printf("after: %g,%g,%g,%g\n", res.X(),res.Y(),res.Z(),res.W()); //printf("by using: \n%g,%g,%g,%g\n",hvMat4<T>::i.X(),hvMat4<T>::i.Y(),hvMat4<T>::i.Z(),hvMat4<T>::i.W()); //printf("%g,%g,%g,%g\n",hvMat4<T>::j.X(),hvMat4<T>::j.Y(),hvMat4<T>::j.Z(),hvMat4<T>::j.W()); //printf("%g,%g,%g,%g\n",hvMat4<T>::k.X(),hvMat4<T>::k.Y(),hvMat4<T>::k.Z(),hvMat4<T>::k.W()); //printf("%g,%g,%g,%g\n",hvMat4<T>::l.X(),hvMat4<T>::l.Y(),hvMat4<T>::l.Z(),hvMat4<T>::l.W()); return (hvVec3<T>)res; } hvVec4<T> apply(const hvVec4<T> &v) const { return this->mult(v); } // apply transform to a vector, result is a new vector // this is the same as for point, but no translation is applied // NOTE: the norm of resulting vector is not preserved hvVec3<T> applyVec3(const hvVec3<T> &v) const { hvMat4<T> m = *this; hvMat3<T> mm= (hvMat3<T>)m; return mm.mult(v); } hvFrame3<T> apply(const hvFrame3<T> &fr) const { hvVec3<T> o=fr.origin(); o = this->apply(o); hvVec3<T> ii=fr.I(); ii = this->applyVec3(ii); hvVec3<T> jj=fr.J(); jj = this->applyVec3(jj); hvVec3<T> kk=fr.K(); kk = this->applyVec3(kk); return hvFrame3<T>(o,ii,jj,kk); } template <class U> void getMatrix(U mm[16]) const { mm[0]=U(hvMat4<T>::i.X()); mm[1]=U(hvMat4<T>::i.Y()); mm[2]=U(hvMat4<T>::i.Z()); mm[3]=U(hvMat4<T>::i.W()); mm[4]=U(hvMat4<T>::j.X()); mm[5]=U(hvMat4<T>::j.Y()); mm[6]=U(hvMat4<T>::j.Z()); mm[7]=U(hvMat4<T>::j.W()); mm[8]=U(hvMat4<T>::k.X()); mm[9]=U(hvMat4<T>::k.Y()); mm[10]=U(hvMat4<T>::k.Z()); mm[11]=U(hvMat4<T>::k.W()); mm[12]=U(hvMat4<T>::l.X()); mm[13]=U(hvMat4<T>::l.Y()); mm[14]=U(hvMat4<T>::l.Z()); mm[15]=U(hvMat4<T>::l.W()); } template <class U> void setMatrix(U mm[16]) { hvMat4<T>::i=hvVec4<T>(mm[0],mm[1],mm[2],mm[3]); hvMat4<T>::j=hvVec4<T>(mm[4],mm[5],mm[6],mm[7]); hvMat4<T>::k=hvVec4<T>(mm[8],mm[9],mm[10],mm[11]); hvMat4<T>::l=hvVec4<T>(mm[12],mm[13],mm[14],mm[15]); } }; } #endif // !defined(AFX_TRANSFORM3_H__33F894B9_F2FB_4902_97D2_D69639938055__INCLUDED_)
8,689
C++
.h
218
36.990826
218
0.613698
ASTex-ICube/semiproctex
39
8
2
LGPL-2.1
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,951
hvMat2.h
ASTex-ICube_semiproctex/Semiproc_synthesis_Src/3rdParty/Externals/hview/hvMat2.h
/* * Code author: Jean-Michel Dischler */ /** * @version 1.0 */ // hvMat2.h: interface for the mat2 class. // // Defines a 2x2 matrix // main operations are: multiplication, addition, multiplication with vector // // By JMD 9/8/06 ////////////////////////////////////////////////////////////////////// #if !defined(AFX_MAT2_H__1544EA11_662A_41FD_8BD3_D7311F73A131__INCLUDED_) #define AFX_MAT2_H__1544EA11_662A_41FD_8BD3_D7311F73A131__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #ifndef M_PI #define M_PI 3.14159265358979323846 #endif #include "hvVec2.h" namespace hview { template <class T> class hvMat2 // : public hviAlgebra<hvMat3<T>,T> { protected: hvVec2<T> i,j; public: // Constructor: defines an identity matrix hvMat2<T>():i(hvVec2<T>(1,0)),j(hvVec2<T>(0,1)) { } // defines a matrix by three 3D vectors each representing a column hvMat2<T>(const hvVec2<T> &a, const hvVec2<T> &b):i(a),j(b) { } // defines a matrix with a single vector u as : M=uu^t (vector u times its transposed u^t) hvMat2<T>(const hvVec2<T> &u) { hvVec2<T> v(u); i.scale(u, v.X()); j.scale(u, v.Y()); } // Selectors : vectors corresponding to columns hvVec2<T> I() const { return i; } hvVec2<T> J() const { return j; } template <class X> hvMat2<T>(const hvMat2<X> &v) { i. template cast<X>(v.I()); j. template cast<X>(v.J()); } // multiply matrix by vector, result is vector hvVec2<T> mult(const hvVec2<T> &v) const { return hvVec2<T> ( i.X()*v.X()+j.X()*v.Y() , i.Y()*v.X()+j.Y()*v.Y() ); } hvVec2<T> operator*(const hvVec2<T> &v) const { return hvVec2<T> ( i.X()*v.X()+j.X()*v.Y() , i.Y()*v.X()+j.Y()*v.Y() ); } // multiply by a scalar value all components void scale(T x) { i.scale(x); j.scale(x); } void operator*=(T x) { i.scale(x); j.scale(x); } void operator/=(T x) { i/=x; j/=x; } void scale(const hvMat2<T> &m, T x) { i.scale(m.i, x); j.scale(m.j, x); } // multiply two matrices void mult(const hvMat2<T> &a, const hvMat2<T> &b) { hvMat2<T> r; r.i=hvVec2<T>( a.i.X()*b.i.X()+a.j.X()*b.i.Y(), a.i.Y()*b.i.X()+a.j.Y()*b.i.Y() ); r.j=hvVec2<T>( a.i.X()*b.j.X()+a.j.X()*b.j.Y(), a.i.Y()*b.j.X()+a.j.Y()*b.j.Y() ); *this = r; } // multiply two matrices hvMat2<T> operator*(const hvMat2<T> &b) const { hvMat2<T> r; r.i=hvVec2<T>( i.X()*b.i.X()+j.X()*b.i.Y(), i.Y()*b.i.X()+j.Y()*b.i.Y() ); r.j=hvVec2<T>( i.X()*b.j.X()+j.X()*b.j.Y(), i.Y()*b.j.X()+j.Y()*b.j.Y() ); return r; } // multiply two matrices void operator*=(const hvMat2<T> &b) { hvMat2<T> r; r.i=hvVec2<T>( i.X()*b.i.X()+j.X()*b.i.Y(), i.Y()*b.i.X()+j.Y()*b.i.Y() ); r.j=hvVec2<T>( i.X()*b.j.X()+j.X()*b.j.Y(), i.Y()*b.j.X()+j.Y()*b.j.Y() ); *this= r; } // divide two matrices (multiply with inverse) void div(const hvMat2<T> &a, const hvMat2<T> &b) { hvMat2<T> r(b); T d = r.det(); if (d==T(0)) { hvFatal("cannot divide by matrice!"); } r.inverse(r, d); mult(a, r); } void operator/=(const hvMat2<T> &b) { hvMat2<T> r(b); T d = r.det(); if (d==T(0)) { hvFatal("cannot divide by matrice!"); } r.inverse(r, d); mult(*this, r); } hvMat2<T> operator/(const hvMat2<T> &b) const { hvMat2<T> r(b); T d = r.det(); if (d==T(0)) { hvFatal("cannot divide by matrice!"); } r.inverse(r, d); r.mult(*this, r); return r; } // add two matrices void add(const hvMat2<T> &a, const hvMat2<T> &b) { i.add(a.i, b.i); j.add(a.j, b.j); } hvMat2<T> operator+(const hvMat2<T> &b) const { hvMat2<T> r; r.i=i+b.i; r.j=j+b.j; return r; } void operator+=(const hvMat2<T> &b) { i+=b.i; j+=b.j; } // sub two matrices void sub(const hvMat2<T> &a, const hvMat2<T> &b) { i.sub(a.i, b.i); j.sub(a.j, b.j); } hvMat2<T> operator-(const hvMat2<T> &b) const { hvMat2<T> r; r.i=i-b.i; r.j=j-b.j; return r; } void operator-=(const hvMat2<T> &b) { i-=b.i; j-=b.j; } // compute determinant (a scalar value) T det() const { return i.X()*j.Y() - i.Y()*j.X(); } // Inverse the matrix a, // works only if det/=0, det must be the determinant of a void inverse(const hvMat2<T> &a, T det) { if (det==T(0)) { hvFatal("cannot inverse with nul det!"); } hvVec2<T> ai(a.i), aj(a.j); i = hvVec3<T>( aj.Y(), -ai.Y() ); j = hvVec3<T>( -aj.X(), ai.X() ); scale(1.0/det); } void inverse(const hvMat2<T> &a) { hvMat2<T> r(a); T dd = r.det(); if (dd==T(0)) { hvFatal("cannot inverse with nul det!"); } inverse(r, dd); } void inverse(T dd) { hvVec2<T> ai(i), aj(j); if (dd==T(0)) { hvFatal("cannot inverse with nul det!"); } scale(1.0/dd); } void inverse() { T dd = det(); if (dd==T(0)) { hvFatal("cannot inverse with nul det!"); } inverse(dd); } // transpose matrix (symetry along the diagonal) void transpose() { hvMat2<T> r; r.i=hvVec2<T>(i.X(), j.X()); r.j=hvVec2<T>(i.Y(), j.Y()); *this = r; } }; } #endif // !defined(AFX_MAT3_H__1544EA11_662A_41FD_8BD3_D7311F73A131__INCLUDED_)
5,049
C++
.h
212
21.193396
109
0.576755
ASTex-ICube/semiproctex
39
8
2
LGPL-2.1
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,953
hvPict.h
ASTex-ICube_semiproctex/Semiproc_synthesis_Src/3rdParty/Externals/hview/hvPict.h
/* * Code author: Jean-Michel Dischler */ /** * @version 1.0 */ // hvPicture.h: interface for the picture class. // ////////////////////////////////////////////////////////////////////// #if !defined(AFX_PICT_H__098453F0_1C38_49E9_A6F4_AABF90AA55E8__INCLUDED_) #define AFX_PICT_H__098453F0_1C38_49E9_A6F4_AABF90AA55E8__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include "hvField2.h" #include "hvColor.h" #include "hvList.h" #include "hvVec2.h" #include <algorithm> #include <list> namespace hview { template <class T> class hvPictRGB ; template <class T> class hvPictRGBA ; class hvBitmap; enum hvPictComponent { HV_RED, HV_GREEN, HV_BLUE, HV_ALPHA, HV_RGB, HV_LUMINANCE } ; enum hvPictMask { HV_GAUSS, HV_EDGE_VERT, HV_EDGE_HORIZ, HV_EDGE_DIAG1, HV_EDGE_DIAG2, HV_DESCR_HORIZ, HV_DESCR_VERT, HV_DESCR_DIAG1, HV_DESCR_DIAG2, HV_DESCR_DOTS } ; //////////////////////////////////////////////////////////// template <class T> class hvPict : public hvField2< T > // T is a scalar type //////////////////////////////////////////////////////////// { public: hvPict<T>() : hvField2< T >(),hvArray2< T >() { } hvPict<T>(int sx, int sy, T nil) : hvField2< T >(sx, sy, nil),hvArray2< T >(sx, sy, nil) { } template <class X> hvPict<T>(const hvArray2<X> &pict) { hvField2< T >::reset(pict.sizeX(), pict.sizeY(), T(0)); int i, j; for (i = 0; i<pict.sizeX(); i++) for (j = 0; j<pict.sizeY(); j++) { update(i, j, T(pict.get(i, j))); } } template <class X> void clone(const hvPict<X> &pict) { hvField2< T >::reset(pict.sizeX(), pict.sizeY(), T(0)); int i,j; for (i=0; i<pict.sizeX(); i++) for (j=0; j<pict.sizeY(); j++) { update(i,j,T(pict.get(i,j))); } } template <class X> void clone(const hvPict<X> &pict, int x, int y, int sx, int sy) { hvField2< T >::reset(sx-x+1, sy-y+1, T(0)); int i,j; for (i=x; i<=sx; i++) for (j=y; j<=sy; j++) { this->update(i-x,j-y,T(pict.get(i,j))); } } hvPict<T>(const hvBitmap &pict, T va, T vb, int x, int y, int sx, int sy): hvField2< T >(sx-x+1, sy-y+1, T(0)), hvArray2< T >(sx-x+1, sy-y+1, T(0)) { int i,j; for (i=x; i<=sx; i++) for (j=y; j<=sy; j++) { if (pict.get(i,j)) update(i-x,j-y,va); else update(i-x,j-y,vb); } } hvPict<T>(const hvBitmap &pict, int border, T scal): hvField2< T >(pict.sizeX(), pict.sizeY(), T(0)), hvArray2< T >(pict.sizeX(), pict.sizeY(), T(0)) { hvPict<int> pi(pict.sizeX(), pict.sizeY(), 0); int count = 1; #if 1 using Vec2i = std::pair<int, int>; std::list< Vec2i > queue; const int neighbX[8] = { -1, 0, 1, -1, 1, -1, 0, 1 }; const int neighbY[8] = { -1, -1, -1, 0, 0, 1, 1, 1 }; for( int j=0; j<pict.sizeY(); ++j ) for (int i = 0; i < pict.sizeX(); ++i) { if (!pict.get(i, j)) continue; for( int n=0; n<8; ++n ) { int ii = i + neighbX[n]; int jj = j + neighbY[n]; if ( ii < 0 || ii >= pict.sizeX() || jj < 0 || jj >= pict.sizeY() || !pict.get(ii, jj)) { queue.push_back(Vec2i(i,j)); pi.update( i, j, 1 ); break; } } } while (!queue.empty()) { Vec2i c = queue.front(); queue.pop_front(); count = std::min( pi.get(c.first, c.second) + 1, border ); for (int n = 0; n < 8; ++n) { int ii = c.first + neighbX[n]; int jj = c.second + neighbY[n]; if (ii >= 0 && ii < pict.sizeX() && jj >= 0 && jj < pict.sizeY() && pict.get(ii, jj) && pi.get(ii, jj) == 0 ) { queue.push_back(Vec2i(ii, jj)); pi.update(ii, jj, count); } } } #else hvBitmap bm; bm=pict; bool cont=true; do { hvBitmap bb; bb.erosion(bm,3,3); hvBitmap back; back=bb; //printf("thinning %d, %d\n", count, bm.count()); ~bb; bb &= bm; for (int j = 0; j<pict.sizeY(); j++) for (int i=0; i<pict.sizeX(); i++) if (bb.get(i,j)) pi.update(i,j,count); if (count<border) count++; bm = back; //if (!cont) { for (i=0; i<pict.sizeX(); i++) for (j=0; j<pict.sizeY(); j++) if (bb.get(i,j)) pi.update(i,j,count); } } while (bm.count()>0); #endif for (int j = 0; j<pict.sizeY(); j++) for (int i=0; i<pict.sizeX(); i++) this->update(i,j,T((double)pi.get(i,j)/(double)count*(double)scal)); } hvPict<T>(bool loop, const hvBitmap &pict, int border, T scal): hvField2< T >(pict.sizeX(), pict.sizeY(), T(0)), hvArray2< T >(pict.sizeX(), pict.sizeY(), T(0)) { hvPict<int> pi(pict.sizeX(), pict.sizeY(), border); hvBitmap bm; bm=pict; int i,j; int count =1; int upd; hvVec2<int> bmin, bmax; pict.box(bmin, bmax); int minx=bmin.X(), miny=bmin.Y(), maxx=bmax.X(), maxy=bmax.Y(); bool cont=true; do { hvBitmap bb; bb.erosionTorus(bm,3,3, minx,miny, maxx, maxy); hvBitmap back; back=bb; //printf("thinning %d, %d\n", count, bm.count()); ~bb; bb &= bm; upd=0; for (i=minx; i<=maxx; i++) for (j=miny; j<=maxy; j++) { if (bb.get(i,j)) { upd++; pi.update(i,j,count); } } count++; if (count>border) cont=false; bm = back; //if (!cont) { for (i=0; i<pict.sizeX(); i++) for (j=0; j<pict.sizeY(); j++) if (bb.get(i,j)) pi.update(i,j,count); } } while (cont && upd>0); for (i=minx; i<=maxx; i++) for (j=miny; j<=maxy; j++) { this->update(i,j,T((double)pi.get(i,j)/(double)border*(double)scal)); } } hvPict<T>(const hvBitmap &pict, int border, T scal, int kernel, int startx, int starty, int endx, int endy): hvField2< T >(pict.sizeX(), pict.sizeY(), T(0)), hvArray2< T >(pict.sizeX(), pict.sizeY(), T(0)) { this->reset(pict.sizeX(), pict.sizeY(), T(0)); hvPict<int> pi(pict.sizeX(), pict.sizeY(), 0); hvBitmap bm; bm=pict; int i,j; int count =1; bool cont=true; do { hvBitmap bb; bb.erosion(bm,kernel,kernel, startx, starty,endx, endy); hvBitmap back; back=bb; //printf("thinning %d\n", count); ~bb; bb &= bm; for (i=startx; i<=endx; i++) for (j=starty; j<=endy; j++) { if (i>=0 && i<bb.sizeX() && j>=0 && j<bb.sizeY()) if (bb.get(i,j)) pi.update(i,j,count); } count++; if (count>border) count=border; bm = back; //if (!cont) { for (i=0; i<pict.sizeX(); i++) for (j=0; j<pict.sizeY(); j++) if (bb.get(i,j)) pi.update(i,j,count); } } while (bm.count()>0); for (i=0; i<pict.sizeX(); i++) for (j=0; j<pict.sizeY(); j++) { this->update(i,j,T((double)pi.get(i,j)/(double)border*(double)scal)); } } template <class X, class Y> hvPict<T>(const hvPict<X> &pict, Y scal, int x, int y, int sx, int sy): hvField2< T >(sx-x+1, sy-y+1, T(0)), hvArray2< T >(sx-x+1, sy-y+1, T(0)) { this->reset(pict.sizeX(), pict.sizeY(), T(0)); int i,j; for (i=0; i<=sx; i++) for (j=0; j<=sy; j++) { this->update(i,j,T(Y(pict.get(i,j))*scal)); } } template <class X> hvPict<T>(const hvPict<X> &pict, double max, double loga, double scal, int x, int y, int sx, int sy) : hvField2< T >(sx - x + 1, sy - y + 1, T(0)), hvArray2< T >(sx - x + 1, sy - y + 1, T(0)) { this->reset(pict.sizeX(), pict.sizeY(), T(0)); int i, j; for (i = 0; i <= sx; i++) for (j = 0; j <= sy; j++) { X val = pict.get(i, j); double vv = log(1.0 + loga*(double)val / max) / log(loga + 1.0); if (vv>1.0) vv = 1.0; this->update(i, j, T(vv*scal)); } } template <class X, class Y> hvPict<T>(const hvPictRGB<X> &pict, Y scal, int x, int y, int sx, int sy); template <class X, class Y> void convert(const hvPictRGB<X> &pict, hvPictComponent cc, Y scal); template <class X, class Y> hvPict<T>(const hvPictRGB<X> &pict, hvPictComponent cc, Y scal, int x, int y, int sx, int sy); template <class X, class Y> hvPict<T>(const hvPictRGBA<X> &pict, Y scal, int x, int y, int sx, int sy); template <class X, class Y> hvPict<T>(const hvPictRGBA<X> &pict, hvPictComponent cc, Y scal, int x, int y, int sx, int sy); template <class X, class Y> hvPict<T>(hvArray1<X> *ft, int size, X loga, Y scal): hvField2< T >(size, size, T(0)), hvArray2< T >(size, size, T(0)) { int i,j; X max = X(0); for (i=0; i<size; i++) for (j=0; j<size; j++) { if (i!=size/2 || j!=size/2) { X val = ft->get(j+i*size); if (max<val) max=val; } } for (i=0; i<size; i++) for (j=0; j<size; j++) { X val = ft->get(j+i*size); val = (X)log(1.0+loga*val/max)/(X)log(loga+1.0); if (val>X(1)) val=X(1); update(j,i, T(Y(val)*scal)); } } template <class X, class Y> hvPict<T>(hvArray1<hvPair<X, X> > *ft, int size, X loga, Y scal, bool amplitude=false): hvField2< T >(size, size, T(0)), hvArray2< T >(size, size, T(0)) { int i,j; X max = X(0); for (i=0; i<size; i++) for (j=0; j<size; j++) { if (i!=size/2 || j!=size/2) { hvPair<X, X> vv = ft->get(j+i*size); X val; if (amplitude) val = sqrt(vv.getLeft()*vv.getLeft()+vv.getRight()*vv.getRight()); else val = vv.getLeft()*vv.getLeft()+vv.getRight()*vv.getRight(); if (max<val) max=val; } } for (i=0; i<size; i++) for (j=0; j<size; j++) { hvPair<X, X> vv = ft->get(j+i*size); X val; if (amplitude) val = sqrt(vv.getLeft()*vv.getLeft()+vv.getRight()*vv.getRight()); else val = vv.getLeft()*vv.getLeft()+vv.getRight()*vv.getRight(); val = (X)log(1.0+loga*val/max)/(X)log(loga+1.0); update(j,i, T(Y(val)*scal)); } } // devides size by factor of 2^(nrec+1), nrec=0 means factor 2, nrec=1 means factor 4, etc. void shrink(hvPict<T> *p, int nrec=0) { if (nrec>0) { hvPict<T> source; source.hvField2<T>::shrink(p); this->shrink(&source, nrec-1); } else hvField2<T>::shrink(p); } // multiplies size by factor of 2^(nrec+1), nrec=0 means factor 2, nrec=1 means factor 4, etc. void enlarge(hvPict<T> *p, int nrec=0) { if (nrec>0) { hvPict<T> source; source.hvField2<T>::enlarge(p); this->enlarge(&source, nrec-1); } else hvField2<T>::enlarge(p); } // applies a deblurring mask of size sx,sy that must be odd numbers void deblur(int niter, int sx, int sy, double scal, double min, double max) { hvField2<T> source; source.clone(this); hvField2<T>:: template deblurs<double>(&source, niter, sx, sy, scal, min, max); } // applies a blurring mask of size sx,sy // scal is the normalization factor, usually sx*sy void blur(T scal, int sx, int sy) { hvField2<T> source; source.clone(this); hvField2<T>:: template blur<double>(&source, sx, sy,(double)(1.0/(double)scal)); } void gaussianBlur(int sx, int sy) { hvField2<T> source; source.clone(this); hvField2<T>::template gaussianBlur<double>(&source, sx, sy); } void gaussianBlur(int sx, int sy, double sig) { hvField2<T> source; source.clone(this); hvField2<T>:: template gaussianBlur<double>(&source, sx, sy, sig); } void gaborFilter(int sx, int sy, double theta, double freq, double sigma, double phase) { hvField2<T> source; source.clone(this); hvField2<T>:: template gaborFilter<double>(&source, sx, sy, theta, freq, sigma, phase); } void anisoGaborFilter(int sx, int sy, double alpha, double theta, double freq, double sigmax, double sigmay, double phase) { hvField2<T> source; source.clone(this); hvField2<T>:: template anisoGaborFilter<double>(&source, sx, sy, alpha, theta, freq, sigmax, sigmay, phase); } // alpha1,2 must be between -PI/4 and 3PI/4 void bandpassFilter(hvPict<T> &res, int pow2, double f1, double f2, double alpha1, double alpha2, double offset, double scale) { int i,j, ii,jj; int NN=1<<pow2; res.hvField2< T >::reset(this->sizeX(),this->sizeY(),T(0)); for (i=0; i<this->sizeX(); i++) { //if (i%10==0) { printf("."); fflush(stdout); } for (j=0; j<this->sizeY(); j++) { hvField2<double> sub(NN,NN,0.0); int xx,yy; for (ii=0; ii<NN; ii++) for (jj=0; jj<NN;jj++) { xx = i+ii-NN/2; if (xx<0) xx+= this->sizeX(); else if (xx>= this->sizeX()) xx-= this->sizeX(); yy = j+jj-NN/2; if (yy<0) yy+= this->sizeY(); else if (yy>= this->sizeY()) yy-= this->sizeY(); sub.update(ii,jj,(double)this->get(xx,yy)); } hvArray1<hvPair<double,double> > *ft = sub.fft(true, scale, offset, pow2); for (ii=0; ii<NN; ii++) for (jj=0; jj<NN; jj++) { double c = ft->get(ii+jj*NN).mod(); double phase = ft->get(ii+jj*NN).phase(); double fx = (double)(ii-NN/2)/(double)NN; double fy = (double)(jj-NN/2)/(double)NN; double ff = sqrt(fx*fx+fy*fy); if (ff<f1 || ff>f2 ) c=0.0; double alpha=hvPair<double,double>(fx,fy).phase(); if (alpha<-M_PI/4.0) alpha+=M_PI; else if (alpha>3.0*M_PI/4.0) alpha-=M_PI; if (alpha<alpha1 || alpha>alpha2) c=0.0; ft->update(ii+jj*NN, hvPair<double,double>( c*cos(phase), -c*sin(phase) )); } for (ii=0; ii<NN; ii++) hvArray1<double>::fft(*ft, pow2,1,ii*NN,false); for (ii=0; ii<NN; ii++) hvArray1<double>::fft(*ft, pow2,NN,ii,false); hvPair<double,double> c = ft->get(NN/2+NN/2*NN); double val=c.mod()*cos(c.phase()); //printf("%d,%d= %g versus %g\n",i,j, (double)this->get(i,j), val); res.update(i,j,val*scale+offset); delete ft; } } } // alpha1,2 must be between -PI/4 and 3PI/4 void bandpassFilterBank(int n, hvPict<T> res[], int pow2, double f1[], double f2[], double alpha1[], double alpha2[], bool inout[], double offset, double scale) { int i,j, k, ii,jj; int NN=1<<pow2; for (i=0; i<n; i++) res[i].hvField2< T >::reset(this->sizeX(), this->sizeY(),T(0)); for (i=0; i<this->sizeX(); i++) { //if (i%10==0) { printf("."); fflush(stdout); } for (j=0; j<this->sizeY(); j++) { hvField2<double> sub(NN,NN,0.0); int xx,yy; for (ii=0; ii<NN; ii++) for (jj=0; jj<NN;jj++) { xx = i+ii-NN/2; if (xx<0) xx+= this->sizeX(); else if (xx>= this->sizeX()) xx-= this->sizeX(); yy = j+jj-NN/2; if (yy<0) yy+= this->sizeY(); else if (yy>= this->sizeY()) yy-= this->sizeY(); sub.update(ii,jj,(double)this->get(xx,yy)); } hvArray1<hvPair<double,double> > *ft = sub.fft(true, scale, offset, pow2); hvArray1<hvPair<double,double> > *rft = new hvArray1<hvPair<double,double> >(NN*NN,hvPair<double,double>(0.0,0.0)); for (k=0; k<n; k++) { for (ii=0; ii<NN; ii++) for (jj=0; jj<NN; jj++) { double c = ft->get(ii+jj*NN).mod(); double phase = ft->get(ii+jj*NN).phase(); double fx = (double)(ii-NN/2)/(double)NN; double fy = (double)(jj-NN/2)/(double)NN; double ff = sqrt(fx*fx+fy*fy); if (ff<f1[k] || ff>f2[k] ) c=0.0; double alpha=hvPair<double,double>(fx,fy).phase(); if (alpha<-M_PI/4.0) alpha+=M_PI; else if (alpha>3.0*M_PI/4.0) alpha-=M_PI; if (inout[k]) { if (alpha<alpha1[k] || alpha>alpha2[k]) c=0.0; } else { if (alpha>=alpha1[k] && alpha<=alpha2[k]) c=0.0; } rft->update(ii+jj*NN, hvPair<double,double>( c*cos(phase), -c*sin(phase) )); } for (ii=0; ii<NN; ii++) hvArray1<double>::fft(*rft, pow2,1,ii*NN,false); for (ii=0; ii<NN; ii++) hvArray1<double>::fft(*rft, pow2,NN,ii,false); hvPair<double,double> c = rft->get(NN/2+NN/2*NN); double val=c.mod()*cos(c.phase()); //printf("%d,%d= %g versus %g\n",i,j, (double)this->get(i,j), val); res[k].update(i,j,val*scale+offset); } delete ft; delete rft; } } } // bilateral filter void bilateral(double sigma, T scal, int sx, int sy) { hvPict<T> pp(this->sizeX(), this->sizeY(), scal); pp.clone(*this); this->bilateral(pp, sigma, scal, sx, sy); } void bilateral(const hvPict<T> &pia, double sigma, T scal, int sx, int sy) { hvField2< T >::reset(pia.sizeX(), pia.sizeY(), T(0)); int i, j, ii, jj; for (i = 0; i<pia.sizeX(); i++) for (j = 0; j<pia.sizeY(); j++) { T cola = pia.get(i, j); double ra = (double)cola / (double)scal; double ww = 0.0; double resa = 0.0; for (ii = -sx / 2; ii <= sx / 2; ii++) for (jj = -sy / 2; jj <= sy / 2; jj++) { if (i + ii >= 0 && i + ii<pia.sizeX() && j + jj >= 0 && j + jj<pia.sizeY()) { cola = pia.get(i + ii, j + jj); double va = (double)cola / (double)scal; double dist = (va - ra)*(va - ra); dist = exp(-dist*sigma*sigma); ww += dist; resa += dist*va; } } resa /= ww; update(i, j, T(resa*scal)); } } void median(int ss) { hvField2<T> source; source.clone(this); hvField2<T>::median(&source, ss); } T maxValue() const { T m = this->get(0,0); int i,j; for (i=0;i<this->sizeX(); i++) for (j=0; j<this->sizeY(); j++) { T v = this->get(i,j); if (v>m) m=v; } return m; } T maxValue(int x, int y, int dx, int dy) const { T m = this->get(0,0); int i,j; for (i=x;i<dx; i++) for (j=y; j<dy; j++) { T v = this->get(i,j); if (v>m) m=v; } return m; } T minValue() const { T m = this->get(0,0); int i,j; for (i=0;i<this->sizeX(); i++) for (j=0; j<this->sizeY(); j++) { T v = this->get(i,j); if (v<m) m=v; } return m; } void normalize(T scal, double percent=1.0, double power=1.0) { int i,j; double max=(double)maxValue()*percent; for (i=0;i<this->sizeX(); i++) for (j=0; j<this->sizeY(); j++) { double v = (double)this->get(i,j)/max; if (v>1.0) v=1.0; this->update(i,j,T(pow(v,power)*(double)scal)); } } void normalize(T scal, T maxval, double percent, double power) { int i,j; double max=(double)maxval*percent; for (i=0;i<this->sizeX(); i++) for (j=0; j<this->sizeY(); j++) { double v = (double)this->get(i,j)/max; if (v>1.0) v=1.0; this->update(i,j,T(pow(v,power)*(double)scal)); } } void rescale(T nmin, T nmax) { int i,j; T min, max; this->minmax(min, max); for (i=0;i<this->sizeX(); i++) for (j=0; j<this->sizeY(); j++) { double v = (double)nmin+((double)nmax-(double)nmin)*((double)this->get(i,j)-(double)min)/((double)max-(double)min); this->update(i,j,T(v)); } } void reverse(T norm) { int i,j; for (i=0;i<this->sizeX(); i++) for (j=0; j<this->sizeY(); j++) { this->update(i,j,norm-this->get(i,j)); } } void clamp() { int i,j; for (i=0;i<this->sizeX(); i++) for (j=0; j<this->sizeY(); j++) { T v = this->get(i,j); if (v<T(0)) v=T(0); this->update(i,j,v); } } void gamma(T scal, double power) { int i,j; for (i=0;i<this->sizeX(); i++) for (j=0; j<this->sizeY(); j++) { T v = this->get(i,j); v = (T)((double)scal*pow((double)v/(double)scal,power)); this->update(i,j,v); } } void contrast(T scal, double power) { int i,j; for (i=0;i<this->sizeX(); i++) for (j=0; j<this->sizeY(); j++) { double v = (double)this->get(i,j); v /= (double)scal; if (v>=0.5) v = pow((v-0.5)*2.0,1.0/power)/2.0+0.5; else v = pow(v*2.0, power)/2.0; this->update(i,j,T(v*(double)scal)); } } double avg() const { int i,j; double v=0.0; for (i=0;i<this->sizeX(); i++) for (j=0; j<this->sizeY(); j++) { v += (double)this->get(i,j); } return v/(double)(this->sizeX()*this->sizeY()); } double avg(const hvBitmap &mask) const { int i,j; double v=0.0; int n=0; for (i=0;i<this->sizeX(); i++) for (j=0; j<this->sizeY(); j++) { if (mask.get(i,j)) { n++; v += (double)this->get(i,j); } } return v/(double)n; } double avgrange(const hvBitmap &mask, T min, T max) const { int i,j; double v=0.0; int n=0; for (i=0;i<this->sizeX(); i++) for (j=0; j<this->sizeY(); j++) { T val = this->get(i,j); if (mask.get(i,j) && val>=min && val<=max) { n++; v += (double)val; } } return v/(double)n; } double avgstat(T &min, T &max, double &var) const { int i,j; double v=0.0, v2=0.0; min=this->get(0,0); max=this->get(0,0); int n=this->sizeX()*this->sizeY(); for (i=0;i<this->sizeX(); i++) for (j=0; j<this->sizeY(); j++) { T val = this->get(i,j); v += (double)val; v2 += (double)val*(double)val; if (val<min) min=val; if (val>max) max=val; } v /= (double)n; var = v2/(double)n-v*v; return v; } template <class X> void histogramm(hvArray1<int> &tab, X min, X max) const { int i,j; for (i=0; i<tab.size(); i++) tab.update(i,0); for (i=0;i<this->sizeX(); i++) for (j=0; j<this->sizeY(); j++) { T v = this->get(i,j); X ind = (X(v)-min)/(max-min); int pos = (int)(ind*X(tab.size()-1)); tab.update(pos,tab.get(pos)+1); } } void avg(T &vmin, T &vmax, T &vmean, T &vmeanmin, T &vmeanmax) const { int i, j; double v = 0.0; for (i = 0; i < this->sizeX(); i++) for (j = 0; j < this->sizeY(); j++) { T val = this->get(i, j); v += (double)val; if (i == 0 && j == 0) { vmin = val; vmax = val; } if (val < vmin) vmin = val; if (val > vmax) vmax = val; } vmean = (T)(v / (double)(this->sizeX()*this->sizeY())); int cmin = 0, cmax = 0; double mmin = 0.0, mmax = 0.0; for (i = 0; i < this->sizeX(); i++) for (j = 0; j < this->sizeY(); j++) { T val = this->get(i, j); if (val < vmean) { cmin++; mmin += (double)val; } if (val > vmean) { cmax++; mmax += (double)val; } } if (cmin > 0) { vmeanmin = (T)(mmin/(double)cmin); } else vmeanmin = vmin; if (cmax > 0) { vmeanmax = (T)(mmax / (double)cmax); } else vmeanmax = vmax; } void avg(T &vmin, T &vmax, T &vmean, T vmeanmin[3], T vmeanmax[3]) const { int i, j; double v = 0.0; for (i = 0; i < this->sizeX(); i++) for (j = 0; j < this->sizeY(); j++) { T val = this->get(i, j); v += (double)val; if (i == 0 && j == 0) { vmin = val; vmax = val; } if (val < vmin) vmin = val; if (val > vmax) vmax = val; } vmean = (T)(v / (double)(this->sizeX()*this->sizeY())); int cmin = 0, cmax = 0; double mmin = 0.0, mmax = 0.0; for (i = 0; i < this->sizeX(); i++) for (j = 0; j < this->sizeY(); j++) { T val = this->get(i, j); if (val <= vmean) { cmin++; mmin += (double)val; } if (val > vmean) { cmax++; mmax += (double)val; } } if (cmin > 0) { vmeanmin[1] = (T)(mmin / (double)cmin); } else vmeanmin[1] = vmin; if (cmax > 0) { vmeanmax[1] = (T)(mmax / (double)cmax); } else vmeanmax[1] = vmax; cmin = 0, cmax = 0; mmin = 0.0, mmax = 0.0; for (i = 0; i < this->sizeX(); i++) for (j = 0; j < this->sizeY(); j++) { T val = this->get(i, j); if (val <= vmean) { if (val <= vmeanmin[1]) { cmin++; mmin += (double)val; } if (val > vmeanmin[1]) { cmax++; mmax += (double)val; } } } if (cmin > 0) { vmeanmin[0] = (T)(mmin / (double)cmin); } else vmeanmin[0]=vmeanmin[1]; if (cmax > 0) { vmeanmin[2] = (T)(mmax / (double)cmax); } else vmeanmin[2]=vmeanmin[1]; cmin = 0, cmax = 0; mmin = 0.0, mmax = 0.0; for (i = 0; i < this->sizeX(); i++) for (j = 0; j < this->sizeY(); j++) { T val = this->get(i, j); if (val > vmean) { if (val <= vmeanmax[1]) { cmin++; mmin += (double)val; } if (val > vmeanmax[1]) { cmax++; mmax += (double)val; } } } if (cmin > 0) { vmeanmax[0] = (T)(mmin / (double)cmin); } else vmeanmax[0] = vmeanmax[1]; if (cmax > 0) { vmeanmax[2] = (T)(mmax / (double)cmax); } else vmeanmax[2] = vmeanmax[1]; } void equalize(T min, T max, T mean, T meanmin, T meanmax) { int i, j; T vmin, vmax, vmean, vmeanmin, vmeanmax; this->avg(vmin, vmax, vmean, vmeanmin, vmeanmax); for (i = 0; i < this->sizeX(); i++) for (j = 0; j < this->sizeY(); j++) { T newv; T val = this->get(i, j); if (val <= vmean) { if (val <= vmeanmin) newv = min + (T)((double)(meanmin - min)*(double)(val - vmin) / (double)(vmeanmin - vmin)); else newv = meanmin + (T)((double)(mean - meanmin)*(double)(val - vmeanmin) / (double)(vmean - vmeanmin)); } else { if (val<= vmeanmax) newv = mean+ (T)((double)(meanmax - mean)*(double)(val - vmean) / (double)(vmeanmax - vmean)); else newv = meanmax + (T)((double)(max - meanmax)*(double)(val - vmeanmax) / (double)(vmax - vmeanmax)); } this->update(i, j, newv); } } void equalize(T min, T max, T mean, T meanmin[3], T meanmax[3]) { int i, j; T vmin, vmax, vmean, vmeanmin[3], vmeanmax[3]; this->avg(vmin, vmax, vmean, vmeanmin, vmeanmax); for (i = 0; i < this->sizeX(); i++) for (j = 0; j < this->sizeY(); j++) { T newv; T val = this->get(i, j); if (val <= vmean) { if (val <= vmeanmin[0]) newv = min + (T)((double)(meanmin[0] - min)*(double)(val - vmin) / (double)(vmeanmin[0] - vmin)); else if (val <= vmeanmin[1]) newv = meanmin[0] + (T)((double)(meanmin[1] - meanmin[0])*(double)(val - vmeanmin[0]) / (double)(vmeanmin[1] - vmeanmin[0])); else if (val <= vmeanmin[2]) newv = meanmin[1] + (T)((double)(meanmin[2] - meanmin[1])*(double)(val - vmeanmin[1]) / (double)(vmeanmin[2] - vmeanmin[1])); else newv = meanmin[2] + (T)((double)(mean - meanmin[2])*(double)(val - vmeanmin[2]) / (double)(vmean - vmeanmin[2])); } else { if (val <= vmeanmax[0]) newv = mean + (T)((double)(meanmax[0] - mean)*(double)(val - vmean) / (double)(vmeanmax[0] - vmean)); else if (val <= vmeanmax[1]) newv = meanmax[0] + (T)((double)(meanmax[1] - meanmax[0])*(double)(val - vmeanmax[0]) / (double)(vmeanmax[1] - vmeanmax[0])); else if (val <= vmeanmax[2]) newv = meanmax[1] + (T)((double)(meanmax[2] - meanmax[1])*(double)(val - vmeanmax[1]) / (double)(vmeanmax[2] - vmeanmax[1])); else newv = meanmax[2] + (T)((double)(max - meanmax[2])*(double)(val - vmeanmax[2]) / (double)(vmax - vmeanmax[2])); } this->update(i, j, newv); } } template <class U> void blendRect(int px, int py, int x, int y, int sx, int sy, const hvPict<T> &example, const hvPict<U> &alpha, U scal, double power, const hvBitmap &mask) { int i,j; for (i=0; i<sx; i++) for (j=0; j<sy; j++) { if (mask.get(x+i,y+j)) { if (px+i>=0 && px+i<this->sizeX() && py+j>=0 && py+j<this->sizeY()) { double coeff = pow((double)alpha.get(x+i,y+j)/(double)scal, power); T col = this->get(px+i,py+j); T colex = example.get(x+i,y+j); T colres = T((double)colex*coeff+(double)col*(1.0-coeff) ); this->update(px+i,py+j,colres); } } } } /* template <class X> void gnoise(X scal, X offset, double fx, double fy) { int i,j; for (i=0;i<sizeX(); i++) for (j=0; j<sizeY(); j++) { X v = (X)hvNoise::gnoise((double)i*(double)fx+23.987, (double)j*(double)fy-6.3327, 42.12345)*scal+offset; update(i,j,T(v)); } } template <class X> void snoise(X scal, X offset, double fx, double fy) { int i,j; for (i=0;i<sizeX(); i++) for (j=0; j<sizeY(); j++) { X v = (X)hvNoise::snoise2((double)i*(double)fx+23.987, (double)j*(double)fy-6.3327)*scal+offset; update(i,j,T(v)); } } */ bool localMaximum(int x, int y, int sx, int sy) const { int i,j; for(i=x-sx; i<=x+sx; i++) for (j=y-sy; j<=y+sy; j++) { if (i>=0 && i<this->sizeX() && j>=0 && j<this->sizeY() && (x!=i || y!=j)) { if (this->get(i,j)>=this->get(x,y)) return false; } } return true; } void minmax(const hvBitmap &mask, T &min, T &max) const { int i,j; bool first=true; for(i=0; i<this->sizeX(); i++) for (j=0; j<this->sizeY(); j++) { if (mask.get(i,j)) { if (first) { min=this->get(i,j); max=this->get(i,j); first=false; } else { T v = this->get(i,j); if (v<min) min=v; if (v>max) max=v; //printf("%d,%d=%d\n", i,j,v); } } } } void minmax(T &min, T &max) const { int i,j; bool first=true; for(i=0; i<this->sizeX(); i++) for (j=0; j<this->sizeY(); j++) { if (first) { min=this->get(i,j); max=this->get(i,j); first=false; } else { T v = this->get(i,j); if (v<min) min=v; if (v>max) max=v; //printf("%d,%d=%d\n", i,j,v); } } } void rotation(const hvPict<T> &bm, float angle) { int i, j, ii, jj; int dx = bm.sizeX() / 2, dy = bm.sizeY() / 2; int sx = 0, sy = 0; for (ii = 0; ii <= 1; ii++) for (jj = 0; jj <= 1; jj++) { int rx = (int)((float)(ii == 0 ? dx : -dx)*cos(angle) - (float)(jj == 0 ? dy : -dy)*sin(angle)); int ry = (int)((float)(ii == 0 ? dx : -dx)*sin(angle) + (float)(jj == 0 ? dy : -dy)*cos(angle)); if (rx > sx) sx = rx; if (ry > sy) sy = ry; } bool cont = true; for (i = 1; i <= (sx < sy ? sx : sy) && cont; i++) { bool valid = true; for (j = -i; j <= i && valid; j++) { int xx = bm.sizeX() / 2 + (int)((float)j*cos(-angle) - (float)i*sin(-angle)); int yy = bm.sizeY() / 2 + (int)((float)j*sin(-angle) + (float)i*cos(-angle)); if (xx < 0 || xx >= bm.sizeX() || yy < 0 || yy >= bm.sizeY()) valid = false; xx = bm.sizeX() / 2 + (int)((float)j*cos(-angle) + (float)i*sin(-angle)); yy = bm.sizeY() / 2 + (int)((float)j*sin(-angle) - (float)i*cos(-angle)); if (xx < 0 || xx >= bm.sizeX() || yy < 0 || yy >= bm.sizeY()) valid = false; xx = bm.sizeX() / 2 + (int)((float)i*cos(-angle) - (float)j*sin(-angle)); yy = bm.sizeY() / 2 + (int)((float)i*sin(-angle) + (float)j*cos(-angle)); if (xx < 0 || xx >= bm.sizeX() || yy < 0 || yy >= bm.sizeY()) valid = false; xx = bm.sizeX() / 2 + (int)(-(float)i*cos(-angle) - (float)j*sin(-angle)); yy = bm.sizeY() / 2 + (int)(-(float)i*sin(-angle) + (float)j*cos(-angle)); if (xx < 0 || xx >= bm.sizeX() || yy < 0 || yy >= bm.sizeY()) valid = false; } if (!valid) cont = false; } int resol = i - 1; this->reset(2 * resol + 1, 2 * resol + 1, false); for (int i = -resol; i <= resol; i++) for (int j = -resol; j <= resol; j++) { int xx = bm.sizeX() / 2 + (int)((float)i*cos(-angle) - (float)j*sin(-angle)); int yy = bm.sizeY() / 2 + (int)((float)i*sin(-angle) + (float)j*cos(-angle)); if (xx >= 0 && xx < bm.sizeX() && yy >= 0 && yy < bm.sizeY()) { this->update(i + resol, j + resol, bm.get(xx, yy)); } } } void rescalex(const hvPict<T> &bm, float scx) { reset((int)((float)bm.sizeX()*scx), bm.sizeY(), false); for (int i = 0; i<this->sizeX(); i++) for (int j = 0; j<this->sizeY(); j++) { int x = (int)((float)i / scx); if (x >= bm.sizeX()) x = bm.sizeX() - 1; update(i, j, bm.get(x, j)); } } void rescalexy(const hvPict<T> &bm, float scx, float scy) { this->reset( (int)( (float)bm.sizeX()*scx ), (int)( (float)bm.sizeY()*scy ), false ); for (int i = 0; i<this->sizeX(); i++) for (int j = 0; j<this->sizeY(); j++) { int x = (int)((float)i / scx); if (x >= bm.sizeX()) x = bm.sizeX() - 1; int y = (int)((float)j / scy); if (y >= bm.sizeY()) y = bm.sizeY() - 1; update(i, j, bm.get(x, y)); } } float mse(const hvPict<T> &pp, float scal) { int i,j; float res=0; for (i=0; i<this->sizeX(); i++) for (j=0; j<this->sizeY(); j++) { float v1 = (float)this->get(i,j)/scal; float v2 = (float)pp.get(i,j)/scal; res += (v1-v2)*(v1-v2); } return res; } void squaredDifference(int px, int py, int dx, int dy, const hvPictRGB<unsigned char> &pia, int ix, int iy, const hvPictRGB<unsigned char> &pib); double minPathH(int ystart, int yend, int mm, int ypath[], double *herr=0) { int i,j; hvArray2<double> sumdiff(this->sizeX(),this->sizeY(),0.0); for (j=0; j<this->sizeY(); j++) sumdiff.update(0,j,(double)this->get(0,j)); hvArray2<int> prev(this->sizeX(),this->sizeY(),0); // compute min cut path for (i=1; i<this->sizeX(); i++) for (j=0; j<this->sizeY(); j++) { int mink; double sumdiffmin=0.0; bool first=true; for (int k=-mm; k<=mm; k++) { if (j+k>=0 && j+k<this->sizeY()) if (sumdiff.get(i-1,j+k)<sumdiffmin || first) { sumdiffmin=sumdiff.get(i-1,j+k); mink=k; first=false; } } sumdiff.update(i,j, sumdiff.get(i-1,j+mink)+(double)this->get(i,j)); prev.update(i,j,mink); /* if (j==0) { if (sumdiff.get(i-1,j)<sumdiff.get(i-1,j+1)) { sumdiff.update(i,j, sumdiff.get(i-1,j)+(double)this->get(i,j)); prev.update(i,j,0); //std::cout<<i<<","<<j<<"="<<sumdiff.get(i,j)<<";"<<sqdiff.get(i,j)<<"\n"; } else { sumdiff.update(i,j, sumdiff.get(i-1,j+1)+(double)this->get(i,j)); prev.update(i,j,1); //std::cout<<i<<","<<j<<"="<<sumdiff.get(i,j)<<";"<<sqdiff.get(i,j)<<"\n"; } } else if (j==this->sizeY()-1) { if (sumdiff.get(i-1,j)<sumdiff.get(i-1,j-1)) { sumdiff.update(i,j, sumdiff.get(i-1,j)+(double)this->get(i,j)); prev.update(i,j,0); //std::cout<<i<<","<<j<<"="<<sumdiff.get(i,j)<<";"<<sqdiff.get(i,j)<<"\n"; } else { sumdiff.update(i,j, sumdiff.get(i-1,j-1)+(double)this->get(i,j)); prev.update(i,j,-1); //std::cout<<i<<","<<j<<"="<<sumdiff.get(i,j)<<";"<<sqdiff.get(i,j)<<"\n"; } } else { if (sumdiff.get(i-1,j)<=sumdiff.get(i-1,j-1) && sumdiff.get(i-1,j)<=sumdiff.get(i-1,j+1)) { sumdiff.update(i,j, sumdiff.get(i-1,j)+(double)this->get(i,j)); prev.update(i,j,0); //std::cout<<i<<","<<j<<"="<<sumdiff.get(i,j)<<";"<<sqdiff.get(i,j)<<"\n"; } else if (sumdiff.get(i-1,j-1)<=sumdiff.get(i-1,j) && sumdiff.get(i-1,j-1)<=sumdiff.get(i-1,j+1)) { sumdiff.update(i,j, sumdiff.get(i-1,j-1)+(double)this->get(i,j)); prev.update(i,j,-1); //std::cout<<i<<","<<j<<"="<<sumdiff.get(i,j)<<";"<<sqdiff.get(i,j)<<"\n"; } else { sumdiff.update(i,j, sumdiff.get(i-1,j+1)+(double)this->get(i,j)); prev.update(i,j,1); //std::cout<<i<<","<<j<<"="<<sumdiff.get(i,j)<<";"<<sqdiff.get(i,j)<<"\n"; } } */ } if (ystart<0) ystart=0; if (yend>=this->sizeY()) yend=this->sizeY()-1; int miny=ystart; double minv=sumdiff.get(this->sizeX()-1,ystart); for (j=ystart+1; j<=yend; j++) if (sumdiff.get(this->sizeX()-1,j)<minv) { minv=sumdiff.get(this->sizeX()-1,j); miny=j; } int posy=miny; double total = 0.0; if (herr != 0) { herr[0] = 0.0; herr[1] = 0.0; } for (i=0; i<this->sizeX(); i++) { //std::cout<<posy<<"\n"; double ee= this->get(this->sizeX() - 1 - i, posy); total += ee; if (herr != 0) { if (i < this->sizeX() / 2) herr[0] += ee; else herr[1] += ee; } ypath[this->sizeX()-1-i]=posy; posy += prev.get(this->sizeX()-1-i,posy); } if (herr != 0) { herr[0] /= (double)(this->sizeX()/2); herr[1] = (double)(this->sizeX() / 2); } return total/(double)(this->sizeX()); } double minPathV(int xstart, int xend, int mm, int xpath[], double *herr = 0) { int i,j; hvArray2<double> sumdiff(this->sizeX(),this->sizeY(),0.0); for (i=0; i<this->sizeX(); i++) sumdiff.update(i,0,(double)this->get(i,0)); hvArray2<int> prev(this->sizeX(),this->sizeY(),0); // compute min cut path for (j=1; j<this->sizeY(); j++) for (i=0; i<this->sizeX(); i++) { int mink; double sumdiffmin=0; bool first=true; for (int k=-mm; k<=mm; k++) { if (i+k>=0 && i+k<this->sizeX()) if (sumdiff.get(i+k,j-1)<sumdiffmin || first) { sumdiffmin=sumdiff.get(i+k,j-1); mink=k; first=false; } } sumdiff.update(i,j, sumdiff.get(i+mink,j-1)+(double)this->get(i,j)); prev.update(i,j,mink); /* if (i==0) { if (sumdiff.get(i,j-1)<sumdiff.get(i+1,j-1)) { sumdiff.update(i,j, sumdiff.get(i,j-1)+(double)this->get(i,j)); prev.update(i,j,0); //std::cout<<i<<","<<j<<"="<<sumdiff.get(i,j)<<";"<<sqdiff.get(i,j)<<"\n"; } else { sumdiff.update(i,j, sumdiff.get(i+1,j-1)+(double)this->get(i,j)); prev.update(i,j,1); //std::cout<<i<<","<<j<<"="<<sumdiff.get(i,j)<<";"<<sqdiff.get(i,j)<<"\n"; } } else if (i==this->sizeX()-1) { if (sumdiff.get(i,j-1)<sumdiff.get(i-1,j-1)) { sumdiff.update(i,j, sumdiff.get(i,j-1)+(double)this->get(i,j)); prev.update(i,j,0); //std::cout<<i<<","<<j<<"="<<sumdiff.get(i,j)<<";"<<sqdiff.get(i,j)<<"\n"; } else { sumdiff.update(i,j, sumdiff.get(i-1,j-1)+(double)this->get(i,j)); prev.update(i,j,-1); //std::cout<<i<<","<<j<<"="<<sumdiff.get(i,j)<<";"<<sqdiff.get(i,j)<<"\n"; } } else { if (sumdiff.get(i,j-1)<=sumdiff.get(i-1,j-1) && sumdiff.get(i,j-1)<=sumdiff.get(i+1,j-1)) { sumdiff.update(i,j, sumdiff.get(i,j-1)+(double)this->get(i,j)); prev.update(i,j,0); //std::cout<<i<<","<<j<<"="<<sumdiff.get(i,j)<<";"<<sqdiff.get(i,j)<<"\n"; } else if (sumdiff.get(i-1,j-1)<=sumdiff.get(i,j-1) && sumdiff.get(i-1,j-1)<=sumdiff.get(i+1,j-1)) { sumdiff.update(i,j, sumdiff.get(i-1,j-1)+(double)this->get(i,j)); prev.update(i,j,-1); //std::cout<<i<<","<<j<<"="<<sumdiff.get(i,j)<<";"<<sqdiff.get(i,j)<<"\n"; } else { sumdiff.update(i,j, sumdiff.get(i+1,j-1)+(double)this->get(i,j)); prev.update(i,j,1); //std::cout<<i<<","<<j<<"="<<sumdiff.get(i,j)<<";"<<sqdiff.get(i,j)<<"\n"; } } */ } if (xstart<0) xstart=0; if (xend>=this->sizeX()) xend=this->sizeX()-1; int minx=xstart; double minv=sumdiff.get(xstart,this->sizeY()-1); for (i=xstart+1; i<=xend; i++) if (sumdiff.get(i,this->sizeY()-1)<minv) { minv=sumdiff.get(i,this->sizeY()-1); minx=i; } int posx=minx; double total = 0.0; if (herr != 0) { herr[0] = 0.0; herr[1] = 0.0; } for (j=0; j<this->sizeY(); j++) { //std::cout<<posx<<"\n"; double ee = this->get(posx, this->sizeY() - 1 - j); total += ee; if (herr != 0) { if (j < this->sizeY() / 2) herr[0] += ee; else herr[1] += ee; } xpath[this->sizeY()-1-j]=posx; posx += prev.get(posx, this->sizeY()-1-j); } if (herr != 0) { herr[0] /= (double)(this->sizeY() / 2); herr[1] = (double)(this->sizeY() / 2); } return total / (double)(this->sizeY()); } void wft(const hvBitmap &mask, int size, float sc, const std::vector<hvVec2<int> > &ff, hvPict<float> *histo) { if (histo->sizeY()!=ff.size()) { hvFatal("histo sizeY does not match number of frequencies!"); } //T min,max; int nn=0; //minmax(mask, min,max); //printf("minmax=%d,%d\n", min,max); hvField2<float> win(size,size,0.0f); hvArray1<hvPair<float,float> > *fft; int i,j, ii, jj; for (i=0; i<histo->sizeX(); i++) for (j=0; j<histo->sizeY(); j++) histo->update(i,j,0.0f); for(i=0; i<this->sizeX(); i++) for (j=0; j<this->sizeY(); j++) if (mask.get(i,j)) { bool cont=true; //printf("."); fflush(stdout); for (ii=0; ii<size && cont; ii++) for (jj=0; jj<size && cont; jj++) { int idx = i+ii-size/2, idy=j+jj-size/2; if (idx>=0 && idx<this->sizeX() && idy>=0 && idy<this->sizeY()) { if (mask.get(idx,idy)) { win.update(ii,jj,(float)this->get(idx,idy)/sc); } else cont=false; } else cont=false; } if (cont) { fft = win.fft(false, 1.0f, 0.0f); for (ii=0; ii<ff.size(); ii++) { hvVec2<int> freq=ff.at(ii); hvPair<float,float> vv = fft->get((freq.X()<0?size+freq.X():freq.X())+(freq.Y()<0?size+freq.Y():freq.Y())*size); float val = vv.getLeft()*vv.getLeft()+vv.getRight()*vv.getRight(); if (freq.X()!=0 || freq.Y()!=0) val = (float)log(1.0+10000.0*val/0.1)/(float)log(10000.0+1.0); int ind = (int)(val*(float)histo->sizeX()); if (ind<0) { std::cout<<"warning : out of bin range"<<val<<"\n"; ind=0; } else if (ind>=histo->sizeX()) { std::cout << "warning : out of bin range" << val << "\n"; ind=histo->sizeX()-1; } histo->update(ind,ii, histo->get(ind,ii)+1.0f); } nn++; delete fft; } } for (i=0; i<histo->sizeX(); i++) for (j=0; j<histo->sizeY(); j++) histo->update(i,j,5.0*histo->get(i,j)/(float)nn); } void wftpyramid(int nlevels, const hvBitmap &mask, int size, float sc, const std::vector<hvVec2<int> > &ff, hvPict<float> *histo[]) { std::cout<<"level 0\n"; wft(mask,size,sc,ff,histo[0]); hvBitmap mm,mm2; mm.shrink(mask,false); hvPict<T> pp,pp2; pp.shrink(this); int i; for (i=1; i<nlevels; i++) { std::cout<<"level "<<i<<"\n"; pp.wft(mm,size,sc,ff,histo[i]); mm2.shrink(mm,false); pp2.shrink(&pp); mm = mm2; pp.clone(pp2); } } void imagefromindex(const hvPict<T> &example, hvArray2<hvVec2<int> > &index) { this->reset(index.sizeX(), index.sizeY(), T(0)); int i, j; for (i = 0; i < this->sizeX(); i++) for (j = 0; j < this->sizeY(); j++) { hvVec2<int> p = index.get(i, j); this->update(i, j, example.get(p.X(), p.Y())); } } ////////////////////////////////////////////////////// double mseGaussian(double normalize, int cx, int cy, double aa, int rx, int ry) { //hvPictRGB<unsigned char> gauss(this->sizeX(), this->sizeY(), hvColRGB<unsigned char>(0)); double sum = 0.0; for (int i = 0; i < this->sizeX(); i++) for (int j = 0; j < this->sizeY(); j++) { double vv = (double)this->get(i, j) / normalize; //double aa = M_PI / 2.0 - M_PI / 8.0*(double)iaa; double px = ((double)(i - cx)*cos(aa) - (double)(j - cy)*sin(aa))/(double)rx; double py = ((double)(i - cx)*sin(aa) + (double)(j - cy)*cos(aa))/(double)ry; double val = vv - exp(-(px*px+py*py)*2.0); //gauss.update(i, j, hvColRGB<unsigned char>((unsigned char)(255.0*exp(-(px*px + py*py)*2.0)))); sum += val*val; } //FILE *fdes = fopen("gauss.ppm", "wb"); //gauss.savePPM(fdes, 1); //fclose(fdes); return sum; } double projectedEnergy(double normalize, int cx, int cy, double aa) { int dd = this->sizeX() < this->sizeY() ? this->sizeX() : this->sizeY(); double sum = 0.0; for (int i = 0; i < this->sizeX(); i++) for (int j = 0; j < this->sizeY(); j++) { double vv = (double)this->get(i, j) / normalize; //double aa = M_PI / 2.0 - M_PI / 8.0*(double)iaa; double dist = ((double)(i - cx)*cos(aa) - (double)(j - cy)*sin(aa)) / (double)dd; sum += vv*exp(-dist*5.0); } return sum; } double findMainAxis(double normalize, int cx, int cy) { int i; const int NANGLE = 8; double maxe, energy[NANGLE]; int imax = 0; for (int iaa = 0; iaa < NANGLE; iaa++) { energy[iaa] = this->projectedEnergy(normalize,cx,cy, M_PI / 2.0 - M_PI / (double)NANGLE*(double)iaa); if (iaa > 0) { if (energy[iaa] > maxe) { imax = iaa; maxe = energy[iaa]; } } else maxe = energy[0]; } double delta = M_PI / (double)NANGLE; double aa = M_PI / 2.0 - M_PI / (double)NANGLE*(double)imax; for (i = 0; i < 5; i++) { double e1 = this->projectedEnergy(normalize, cx, cy, aa - delta); double e2 = this->projectedEnergy(normalize, cx, cy, aa + delta); if (e1 > e2) { aa = aa - delta / 2.0; } else { aa = aa + delta / 2.0; } delta /= 2.0; } return aa; } void findBestMatchingGaussian(double normalize, int cx, int cy, int &rx, int &ry, double &a) { a = this->findMainAxis(normalize,cx, cy); //printf("main axis=%g\n", a); int i, j; const int NSTEP = 32; int dd = (this->sizeX() < this->sizeY() ? this->sizeX() : this->sizeY())/NSTEP/8; double mine; int imax = 0, jmax=0; for (i = 0; i < NSTEP; i++) for (j = 0; j <= i; j++) { double en = this->mseGaussian(normalize, cx, cy, a, i*dd+dd, j*dd+dd); //printf("%d,%d -> %g\n", dd + i*dd, dd + j*dd, en); //char buff[10]; //fgets(buff, 10, stdin); if (i!= 0 || j!=0) { if (en < mine) { imax = i; jmax = j; mine = en; } } else mine = en; } rx = imax*dd+dd; ry = jmax*dd+dd; } }; } #endif // !efined(AFX_PICT_H__098453F0_1C38_49E9_A6F4_AABF90AA55E8__INCLUDED_)
42,682
C++
.h
1,246
30.563403
211
0.557864
ASTex-ICube/semiproctex
39
8
2
LGPL-2.1
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,954
hvLinearTransform2.h
ASTex-ICube_semiproctex/Semiproc_synthesis_Src/3rdParty/Externals/hview/hvLinearTransform2.h
/* * Code author: Jean-Michel Dischler */ /** * @version 1.0 */ // LinearTransform2.h: interface for the LinearTransform2 class. // // Define a linear transform in 2D space (scaling, translation, rotation, etc.) // // LinearTransform2 derives from matrix 3x3 (homogenous coordinates) // A main operation consists in applying the transform to 2D points // // By JMD 18/1/08 ////////////////////////////////////////////////////////////////////// #if !defined(AFX_LINEARTRANSFORM2_H__33F894B9_F2FB_4902_97D2_D69639938055__INCLUDED_) #define AFX_LINEARTRANSFORM2_H__33F894B9_F2FB_4902_97D2_D69639938055__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include "hvMat3.h" #include "hviTransform.h" namespace hview { template <class T> class hvLinearTransform2 : public hvMat3<T>, public hviTransform<hvLinearTransform2<T>, hvVec2<T> > { public: // constructor: defines identity transform hvLinearTransform2() { } template <class X> void cast(const hvLinearTransform2<X> &v) { hvMat3<T>::i.cast<X>(v.I()); hvMat3<T>::j.cast<X>(v.J()); hvMat3<T>::k.cast<X>(v.K()); } void setIdentity() { hvMat3<T>::i=hvVec3<T>(1,0,0); hvMat3<T>::j=hvVec3<T>(0,1,0); hvMat3<T>::k=hvVec3<T>(0,0,1); } // List of transforms: each is composed with the current one // shift of vector v void translation(const hvVec2<T> &v) { hvMat3<T> m(hvVec3<T>(1,0,0), hvVec3<T>(0,1,0), hvVec3<T>(v.X(),v.Y(),1)); this->mult(*this, m); } // scale the three components by factors given by v void scale(const hvVec2<T> &v) { hvMat3<T> m(hvVec3<T>(v.X(),0,0), hvVec3<T>(0,v.Y(),0), hvVec3<T>(0,0,1)); this->mult(*this, m); } // rotation by angle a in radiant void rot(T a) { hvMat3<T> m( hvVec3<T>(cos(a), sin(a), 0.0), hvVec3<T>(-sin(a), cos(a), 0.0), hvVec3<T>(0.0, 0.0, 1.0) ); this->mult(*this, m); } // compose two transforms with each other void compose(const hvLinearTransform2<T> &a, const hvLinearTransform2<T> &b) { this->mult(a,b); } // apply a transform to a 2D point, result is a 2D point hvVec2<T> apply(const hvVec2<T> &v) const { hvVec3<T> u(v.X(), v.Y(), 1); hvVec3<T> r=this->mult(u); return hvVec2<T>(r.X()/r.Z(),r.Y()/r.Z()); } hvVec3<T> apply(const hvVec3<T> &v) const { return this->mult(v); } // apply transform to a vector, result is a new vector // this is the same as for point, but no translation is applied // NOTE: the norm of resulting vector is not preserved hvVec2<T> applyVec2(const hvVec2<T> &v) const { hvMat3<T> m = *this; hvMat2<T> mm= (hvMat2<T>)m; return mm.mult(v); } }; } #endif // !defined(AFX_TRANSFORM2_H__33F894B9_F2FB_4902_97D2_D69639938055__INCLUDED_)
2,665
C++
.h
68
36.897059
153
0.663817
ASTex-ICube/semiproctex
39
8
2
LGPL-2.1
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,955
hvPictRGB.h
ASTex-ICube_semiproctex/Semiproc_synthesis_Src/3rdParty/Externals/hview/hvPictRGB.h
/* * Publication: Semi-Procedural Textures Using Point Process Texture Basis Functions * Computer Graphics Forum (EGSR 2020 special issue) * Authors: P. Guehl , R. AllEgre , J.-M. Dischler, B. Benes , and E. Galin * * Code author: Jean-Michel Dischler */ /** * @version 1.0 */ #ifndef _HV_SYNTHESIZER_ #define _HV_SYNTHESIZER_ /****************************************************************************** ******************************* INCLUDE SECTION ****************************** ******************************************************************************/ // System #include <cstdio> #include <cstring> // STL #include <numeric> #include <chrono> #include <iostream> // Project #include "hvLinearTransform3.h" #include "hvBitmap.h" #include "hvField2.h" #include "hvColor.h" #include "hvPict.h" #include "MyThreadPool.h" #include "hvNoise.h" /** * MACRO */ #define USE_MULTITHREADED_SYNTHESIS #define USE_NO_TEMPORARY_IMAGE_EXPORT /** * MACRO used to remove guidance constraints at 2nd correction step * => this forces to reinject exemplar data similarity into optimization */ #define USE_NO_GUIDANCE_RELAXATION namespace hview { // from Ward's RGBE images const int MAX_SYNTHESIS_PIXEL_LIST = 5; typedef struct { int valid; /* indicate which fields are valid */ char programtype[16]; /* listed at beginning of file to identify it * after "#?". defaults to "RGBE" */ float gamma; /* image has already been gamma corrected with * given gamma. defaults to 1.0 (no correction) */ float exposure; /* a value of 1.0 in an image corresponds to * <exposure> watts/steradian/m^2. * defaults to 1.0 */ } rgbe_header_info; /* flags indicating which fields in an rgbe_header_info are valid */ #define RGBE_VALID_PROGRAMTYPE 0x01 #define RGBE_VALID_GAMMA 0x02 #define RGBE_VALID_EXPOSURE 0x04 template <class T> class hvPictRGBA; //////////////////////////////////////////////////////////// template <class T> class hvPictRGB : public hvField2< hvColRGB<T> > //////////////////////////////////////////////////////////// { public: hvPictRGB<T>() : hvField2< hvColRGB<T> >(),hvArray2< hvColRGB<T> >() { } hvPictRGB<T>(int sx, int sy, const hvColRGB<T> &nil) : hvField2< hvColRGB<T> >(sx, sy, nil),hvArray2< hvColRGB<T> >(sx, sy, nil) { } void reset(int sx, int sy,const hvColRGB<T> &nil) { hvField2< hvColRGB<T> >::reset(sx,sy, nil); } void reset() { hvField2< hvColRGB<T> >::reset(); } void clone(const hvPictRGB<T> &pict,int x, int y, int sx, int sy) { hvField2< hvColRGB<T> >::reset(sx-x+1, sy-y+1, hvColRGB<T>(0)); int i,j; for (i=x; i<=sx; i++) for (j=y; j<=sy; j++) { this->update(i-x,j-y,pict.get(i,j)); } } template <class U> void clone(const hvPictRGB<U> &pict, U scalu, U gamma, U scalt, int x, int y, int sx, int sy) { hvField2< hvColRGB<T> >::reset(sx-x+1, sy-y+1, hvColRGB<T>(0)); int i,j; for (i=x; i<= sx; i++) for (j=y; j<= sy; j++) { hvColRGB<U> col = pict.get(i,j); col.scale(1.0/scalu); col.gamma(1.0, gamma); this->update(i-x,j-y,hvColRGB<T>( (T)(scalt*col.RED()),(T)(scalt*col.GREEN()),(T)(scalt*col.BLUE()) )); } } hvPictRGB<T>(const hvBitmap &pict, const hvColRGB<T> &va, const hvColRGB<T> &vb): hvField2< hvColRGB<T> >(pict.sizeX(), pict.sizeY(), hvColRGB<T>(0)), hvArray2< hvColRGB<T> >(pict.sizeX(), pict.sizeY(), hvColRGB<T>(0)) { int i,j; for (i=0; i<pict.sizeX(); i++) for (j=0; j<pict.sizeY(); j++) { if (pict.get(i,j)) this->update(i,j,va); else this->update(i,j,vb); } } void convert(const hvBitmap &pict, const hvColRGB<T> &va, const hvColRGB<T> &vb) { hvField2< hvColRGB<T> >::reset(pict.sizeX(), pict.sizeY(), hvColRGB<T>(0)); //hvArray2< hvColRGB<T> >::reset(pict.sizeX(), pict.sizeY(), hvColRGB<T>(0)); int i,j; for (i=0; i<pict.sizeX(); i++) for (j=0; j<pict.sizeY(); j++) { if (pict.get(i,j)) this->update(i,j,va); else this->update(i,j,vb); } } hvPictRGB<T>(const hvPictRGBA<T> &pict, hvPictComponent cc): hvField2< hvColRGB<T> >(pict.sizeX(), pict.sizeY(), hvColRGB<T>(0)), hvArray2< hvColRGB<T> >(pict.sizeX(), pict.sizeY(), hvColRGB<T>(0)) { int i,j; for (i=0; i<pict.sizeX(); i++) for (j=0; j<pict.sizeY(); j++) { hvColRGB<T> v; hvColRGBA<T> co = pict.get(i,j); switch(cc) { case HV_RED: v=hvColRGB<T>(co.RED()); break; case HV_GREEN: v=hvColRGB<T>(co.GREEN()); break; case HV_BLUE: v=hvColRGB<T>(co.BLUE()); break; case HV_ALPHA: v=hvColRGB<T>(co.ALPHA()); break; case HV_RGB: v=hvColRGB<T>(co); break; default: v = hvColRGB<T>(co.luminance()); } this->update(i,j,v); } } hvPictRGB<T>(const hvPictRGB<T> &pict, hvPictComponent cc): hvField2< hvColRGB<T> >(pict.sizeX(), pict.sizeY(), hvColRGB<T>(0)), hvArray2< hvColRGB<T> >(pict.sizeX(), pict.sizeY(), hvColRGB<T>(0)) { int i,j; for (i=0; i<pict.sizeX(); i++) for (j=0; j<pict.sizeY(); j++) { hvColRGB<T> v; hvColRGB<T> co = pict.get(i,j); switch(cc) { case HV_RED: v=hvColRGB<T>(co.RED()); break; case HV_GREEN: v=hvColRGB<T>(co.GREEN()); break; case HV_BLUE: v=hvColRGB<T>(co.BLUE()); break; case HV_RGB: v=hvColRGB<T>(co); break; default: v = hvColRGB<T>(co.luminance()); } this->update(i,j,v); } } template <class U, class V> hvPictRGB(const hvPict<U> &p, V scal); template <class U, class V> hvPictRGB(const hvPict<U> &p, V scal, V shift); template <class U, class V> hvPictRGB(const hvPict<U> &p, V scal, int x, int y, int sx, int sy); template <class U, class V> void convert(const hvPict<U> &p, V scal, int x, int y, int sx, int sy); template <class U, class V> void convertloga(const hvPict<U> &p, V loga, V max, V scal, int x, int y, int sx, int sy); template <class U, class V> hvPictRGB(const hvPict<U> &p, V scal, V min, V max); template <class U> hvPictRGB(const hvPict<U> &p, const std::vector<hvColRGB<unsigned char> > &lcol); // choose RGB components from two input void merge(const hvPictRGB<T> &pa, const hvPictRGB<T> &pb, bool rr, bool gg, bool bb) { int i,j; hvField2< hvColRGB<T> >::reset(pa.sizeX(), pa.sizeY(), hvColRGB<T>(0)); for (i=0; i<this->sizeX(); i++) for (j=0; j<this->sizeY(); j++) { hvColRGB<T> ca = pa.get(i,j); hvColRGB<T> cb = pb.get(i,j); hvColRGB<T> v=hvColRGB<T>(rr?ca.RED():cb.RED(), gg?ca.GREEN():cb.GREEN(), bb?ca.BLUE():cb.BLUE()); this->update(i,j,v); } } // keep only some RGB components void extract(bool rr, bool gg, bool bb, T cr, T cg, T cb) { int i,j; for (i=0; i<this->sizeX(); i++) for (j=0; j<this->sizeY(); j++) { hvColRGB<T> co = this->get(i,j); hvColRGB<T> v=hvColRGB<T>(rr?co.RED():cr,gg?co.GREEN():cg,bb?co.BLUE():cb); this->update(i,j,v); } } // Convert into HSV color space void toHSV(const hvPictRGB<T> &p, T scal, hvColRGB<double> weights=hvColRGB<double>(1.0,1.0,1.0)) { int i,j; hvField2< hvColRGB<T> >::reset(p.sizeX(), p.sizeY(), hvColRGB<T>(0)); for (i=0; i<p.sizeX(); i++) for (j=0; j<p.sizeY(); j++) { hvColRGB<T> val = p.get(i,j); hvColRGB<T> valhsv; valhsv.tohsv(val, scal); this->update(i,j,hvColRGB<T>(T((double)valhsv.RED()*weights.RED()), T((double)valhsv.GREEN()*weights.GREEN()), T((double)valhsv.BLUE()*weights.BLUE()))); } } // Convert into XYZ color space void toXYZ(const hvPictRGB<T> &p, T scal, hvColRGB<double> weights=hvColRGB<double>(1.0,1.0,1.0)) { int i,j; hvField2< hvColRGB<T> >::reset(p.sizeX(), p.sizeY(), hvColRGB<T>(0)); for (i=0; i<p.sizeX(); i++) for (j=0; j<p.sizeY(); j++) { hvColRGB<T> val = p.get(i,j); hvColRGB<T> valhsv; valhsv.toxyz(val, scal); this->update(i,j,hvColRGB<T>(T((double)valhsv.RED()*weights.RED()), T((double)valhsv.GREEN()*weights.GREEN()), T((double)valhsv.BLUE()*weights.BLUE()))); } } // Convert into LUV color space void toLUV(const hvPictRGB<T> &p, T scal, hvColRGB<double> weights=hvColRGB<double>(1.0,1.0,1.0)) { int i,j; hvField2< hvColRGB<T> >::reset(p.sizeX(), p.sizeY(), hvColRGB<T>(0)); for (i=0; i<p.sizeX(); i++) for (j=0; j<p.sizeY(); j++) { hvColRGB<T> val = p.get(i,j); hvColRGB<T> valhsv; valhsv.toLuv(val, scal); this->update(i,j,hvColRGB<T>(T((double)valhsv.RED()*weights.RED()), T((double)valhsv.GREEN()*weights.GREEN()), T((double)valhsv.BLUE()*weights.BLUE()))); } } // Convert from XYZ color space back to RGB void fromXYZ(const hvPictRGB<T> &p, T scal, hvColRGB<double> weights=hvColRGB<double>(1.0,1.0,1.0)) { int i,j; hvField2< hvColRGB<T> >::reset(p.sizeX(), p.sizeY(), hvColRGB<T>(0)); for (i=0; i<p.sizeX(); i++) for (j=0; j<p.sizeY(); j++) { hvColRGB<T> val = p.get(i,j); hvColRGB<T> valhsv; valhsv.fromxyz(val, scal); this->update(i,j,hvColRGB<T>(T((double)valhsv.RED()*weights.RED()), T((double)valhsv.GREEN()*weights.GREEN()), T((double)valhsv.BLUE()*weights.BLUE()))); } } // Convert from LUV color space back to RGB void fromLUV(const hvPictRGB<T> &p, T scal, hvColRGB<double> weights=hvColRGB<double>(1.0,1.0,1.0)) { int i,j; hvField2< hvColRGB<T> >::reset(p.sizeX(), p.sizeY(), hvColRGB<T>(0)); for (i=0; i<p.sizeX(); i++) for (j=0; j<p.sizeY(); j++) { hvColRGB<T> val = p.get(i,j); hvColRGB<T> valhsv; valhsv.fromLuv(val, scal); this->update(i,j,hvColRGB<T>(T((double)valhsv.RED()*weights.RED()), T((double)valhsv.GREEN()*weights.GREEN()), T((double)valhsv.BLUE()*weights.BLUE()))); } } // difference between two images of same resolution void difference(const hvPictRGB<T> &pia,const hvPictRGB<T> &pib) { hvField2< hvColRGB<T> >::reset(pia.sizeX(), pia.sizeY(), hvColRGB<T>(0)); int i,j; for (i=0; i<pia.sizeX(); i++) for (j=0; j<pia.sizeY(); j++) { hvColRGB<T> cola = pia.get(i,j); hvColRGB<T> colb = pib.get(i,j); hvColRGB<T> cold; cold.difference(cola,colb); this->update(i,j,cold); } } // difference between two images of same resolution void difference(const hvPictRGB<T> &pia,const hvPictRGB<T> &pib, double scale, double offset) { hvField2< hvColRGB<T> >::reset(pia.sizeX(), pia.sizeY(), hvColRGB<T>(0)); int i,j; for (i=0; i<pia.sizeX(); i++) for (j=0; j<pia.sizeY(); j++) { hvColRGB<T> cola = pia.get(i,j); hvColRGB<T> colb = pib.get(i,j); hvColRGB<T> cold; cold.difference(cola,colb, scale, offset); this->update(i,j,cold); } } // difference between two images of same resolution void differenceMask(double sqdthresh, const hvPictRGB<T> &pi, hvBitmap &diff) { diff.reset(pi.sizeX(), pi.sizeY(), true); int i,j; for (i=0; i<pi.sizeX(); i++) for (j=0; j<pi.sizeY(); j++) { hvColRGB<T> cola = pi.get(i,j); hvColRGB<T> colb = this->get(i,j); diff.set(i,j,(cola.squaredDifference(colb)>sqdthresh)); } } void squaredDifference(int px, int py, int dx, int dy, const hvPictRGB<unsigned char> &pia, int ix, int iy, const hvPictRGB<unsigned char> &pib); double meansquareDifference(const hvPictRGB<T> &pi, hvBitmap &mask) { int i,j; int count=0; double sum=0.0; for (i=0; i<pi.sizeX(); i++) for (j=0; j<pi.sizeY(); j++) { if (mask.get(i,j)) { hvColRGB<T> cola = pi.get(i,j); hvColRGB<T> colb = this->get(i,j); sum+=cola.squaredDifference(colb); count++; } } return sum/(double)count; } double meansquareDifference(int u, int v, const hvPictRGB<T> &pi, int x, int y, int sx, int sy) { int i,j; int count=0; double sum=0.0; for (i=-sx; i<=sx; i++) for (j=-sy; j<=sy; j++) { int xx = x+i; if (xx<0) xx+= pi.sizeX(); else if (xx>=pi.sizeX()) xx-=pi.sizeX(); int yy = y+j; if (yy<0) yy+= pi.sizeY(); else if (yy>=pi.sizeY()) yy-=pi.sizeY(); int uu = u+i; if (uu<0) uu+= this->sizeX(); else if (uu>=this->sizeX()) uu-=this->sizeX(); int vv = v+j; if (vv<0) vv+= this->sizeY(); else if (vv>=this->sizeY()) vv-=this->sizeY(); hvColRGB<T> cola = pi.get(xx,yy); hvColRGB<T> colb = this->get(uu,vv); sum+=cola.squaredDifference(colb)/3.0; count++; } return sum/(double)count; } // applies a blurring mask of size sx,sy // scal is the normalization factor, usually sx*sy void blur(T scal, int sx, int sy) { hvField2<hvColRGB<T> > source; source.clone(this); hvField2<hvColRGB<T> >:: template blur<hvColRGB<double> >(&source, sx, sy, hvColRGB<double>(1.0/(double)scal)); } void gaussianBlur(int sx, int sy) { hvField2<hvColRGB<T> > source; source.clone(this); hvField2<hvColRGB<T> >:: template gaussianBlur<hvColRGB<double> >(&source, sx, sy); } // applies a deblurring mask of size sx,sy void deblur(int niter, int sx, int sy, double scal, double min, double max) { hvField2<hvColRGB<T> > source; source.clone(this); hvField2<hvColRGB<T> >:: template deblur<hvColRGB<double> >(&source, niter, sx, sy, scal, min, max); } // Difference of Gaussians void DoG(const hvPictRGB<T> &pia, int sx, int sy, int nrec=-1) { hvPictRGB<T> pi, pib; pi.clone(pia, 0, 0, pia.sizeX()-1, pia.sizeY()-1); if (nrec>=0) { pib.shrink(&pi,nrec); pi.clone(pib,0,0,pib.sizeX()-1,pib.sizeY()-1); } else pib.clone(pia, 0, 0, pia.sizeX()-1, pia.sizeY()-1); pib.gaussianBlur(sx,sy); this->difference(pi,pib); } // Difference of Gaussians void DoG(const hvPictRGB<T> &pia, int sx, int sy, double scale, double offset) { hvPictRGB<T> pib; pib.clone(pia, 0, 0, pia.sizeX()-1, pia.sizeY()-1); pib.gaussianBlur(sx,sy); this->difference(pia,pib, scale, offset); } // Difference of Gaussians void DoG(hvPict<T> &pires, int sx, int sy) { int i,j; hvPictRGB<T> pi; pi.clone(*this, 0, 0, this->sizeX()-1, this->sizeY()-1); pi.gaussianBlur(sx,sy); pires.reset(this->sizeX(), this->sizeY(),0); for (i=0; i<pi.sizeX(); i++) for (j=0; j<pi.sizeY(); j++) { pires.update(i,j,(T)(sqrt(pi.get(i,j).squaredDifference(this->get(i,j))/3.0))); } } void histogramm(double *histo, int NN, double norm, int x, int y, int fx, int fy, hvPictComponent comp) { int i,j; for (i=0; i<NN; i++) histo[i]=0.0; for (i=x; i<=fx; i++) for (j=y; j<=fy; j++) { hvColRGB<T> col = this->get(i,j); double v; switch(comp) { case HV_RED: v=col.RED(); break; case HV_GREEN: v=col.GREEN(); break; case HV_BLUE: v=col.BLUE(); break; default: v = col.luminance(); } v /= norm; int bin = v*(double)NN; if (bin<0) bin=0; else if (bin>=NN-1) bin=NN-1; histo[bin]+=1.0; } for (i=0; i<NN; i++) histo[i]/=(double)((fx-x+1)*(fy-y+1)); } // checks if R,G,B values are local max in mask size [-1,1] , returns value or 0 if not max hvColRGB<T> isLocalMaximum(const hvPictRGB<T> &dog2, int x, int y) const { hvColRGB<T> vxy = this->get(x,y); int i,j; bool rr=true, gg=true, bb=true; for (i=-1; i<=1; i++) for (j=-1; j<=1; j++) { if (x+i>=0 && x+i<this->sizeX() && y+j>=0 && y+j<this->sizeY()) { hvColRGB<T> v = this->get(x+i,y+j); if (vxy.RED()<v.RED()) rr=false; if (vxy.GREEN()<v.GREEN()) gg=false; if (vxy.BLUE()<v.BLUE()) bb=false; v = dog2.get((x+i)/2,(y+j)/2); if (vxy.RED()<v.RED()) rr=false; if (vxy.GREEN()<v.GREEN()) gg=false; if (vxy.BLUE()<v.BLUE()) bb=false; } } return hvColRGB<T>(rr?vxy.RED():T(0),gg?vxy.GREEN():T(0),bb?vxy.BLUE():T(0)); } // computes local gradient using central differences along X and Y axes void gradient(int x, int y, T scale, hvColRGB<double> *dx, hvColRGB<double> *dy) const { if (x-1>=0 && x+1<this->sizeX()) { hvColRGB<T> cola= this->get(x-1,y); hvColRGB<T> colb= this->get(x+1,y); *dx=hvColRGB<double>((double)colb.X()/(double)scale-(double)cola.X()/(double)scale, (double)colb.Y()/(double)scale-(double)cola.Y()/(double)scale, (double)colb.Z()/(double)scale-(double)cola.Z()/(double)scale); } if (y-1>=0 && y+1<this->sizeY()) { hvColRGB<T> cola= this->get(x,y-1); hvColRGB<T> colb= this->get(x,y+1); *dy=hvColRGB<double>((double)colb.X()/(double)scale-(double)cola.X()/(double)scale, (double)colb.Y()/(double)scale-(double)cola.Y()/(double)scale, (double)colb.Z()/(double)scale-(double)cola.Z()/(double)scale); } } // devides size by factor of 2^(nrec+1), nrec=0 means factor 2, nrec=1 means factor 4, etc. void shrink(hvPictRGB<T> *p, int nrec=0) { if (nrec>0) { hvPictRGB<T> source; source.shrink(p,0); this->shrink(&source, nrec-1); } else { this->reset(p->sizeX()/2, p->sizeY()/2, hvColRGB<T>()); int ii,jj; for (ii=0; ii<this->sizeX(); ii++) for (jj=0; jj<this->sizeY(); jj++) { hvColRGB<T> cc[4]; cc[0]=p->get(2*ii,2*jj); cc[1]=p->get(2*ii+1,2*jj); cc[2]=p->get(2*ii+1,2*jj+1); cc[3]=p->get(2*ii,2*jj+1); hvColRGB<T> col; col.mean(4,cc); this->update(ii,jj,col); } } } void shrinkx(hvPictRGB<T> *p, int nrec=0) { if (nrec>0) { hvPictRGB<T> source; source.shrinkx(p,0); this->shrinkx(&source, nrec-1); } else { this->reset(p->sizeX()/2, p->sizeY(), hvColRGB<T>()); int ii,jj; for (ii=0; ii<this->sizeX(); ii++) for (jj=0; jj<this->sizeY(); jj++) { hvColRGB<T> cc[2]; cc[0]=p->get(2*ii,jj); cc[1]=p->get(2*ii+1,jj); hvColRGB<T> col; col.mean(2,cc); this->update(ii,jj,col); } } } void shrinky(hvPictRGB<T> *p, int nrec=0) { if (nrec>0) { hvPictRGB<T> source; source.shrinky(p,0); this->shrinky(&source, nrec-1); } else { this->reset(p->sizeX(), p->sizeY()/2, hvColRGB<T>()); int ii,jj; for (ii=0; ii<this->sizeX(); ii++) for (jj=0; jj<this->sizeY(); jj++) { hvColRGB<T> cc[2]; cc[0]=p->get(ii,2*jj); cc[1]=p->get(ii,2*jj+1); hvColRGB<T> col; col.mean(2,cc); this->update(ii,jj,col); } } } // multiplies size by factor of 2^(nrec+1), nrec=0 means factor 2, nrec=1 means factor 4, etc. void enlarge(hvPictRGB<T> *p, int nrec=0) { if (nrec>0) { hvPictRGB<T> source; source.hvField2<hvColRGB<T> >::enlarge(p); this->enlarge(&source, nrec-1); } else hvField2<hvColRGB<T> >::enlarge(p); } // applies a local operator mm on a mask of size [-size,+size] hvVec3<double> maskPixel(T scal, int size, int x, int y, hvPictMask mm) const { int ii,jj,i,j; hvVec3<double> res(0.0); for (ii=-size; ii<=size; ii++) for (jj=-size; jj<=size; jj++) { int px = x+ii; if (px<0) px=0; else if (px>= this->sizeX()) px= this->sizeX()-1; int py = y+jj; if (py<0) py=0; else if (py>= this->sizeY()) py= this->sizeY()-1; hvColRGB<T> v = this->get(px,py); hvVec3<double> vd((double)v.RED()/(double)scal,(double)v.GREEN()/(double)scal,(double)v.BLUE()/(double)scal); switch(mm) { case HV_EDGE_VERT: if (ii<0) res-=vd; else if (ii>0) res+=vd; break; case HV_EDGE_HORIZ: if (jj<0) res-=vd; else if (jj>0) res+=vd; break; case HV_EDGE_DIAG1: if (jj>ii) res-=vd; else if (jj<ii) res+=vd; break; case HV_EDGE_DIAG2: if (jj>-ii) res-=vd; else if (jj<-ii) res+=vd; break; case HV_DESCR_VERT: if (ii<0) res-=vd; else res+=vd; break; case HV_DESCR_HORIZ: if (jj<0) res-=vd; else res+=vd; break; case HV_DESCR_DIAG1: if ((ii<0 && jj<0)||(ii>=0 && jj>=0)) res-=vd; else res+=vd; break; case HV_DESCR_DIAG2: if ((ii<0 && jj>0)||(ii>=0 && jj<=0)) res-=vd; else res+=vd; break; //case HV_DESCR_DOTS: i=ii<0?-ii:ii; j=jj<0?-jj:jj; i/=2; j/=2; if ((i%2==0 && j%2!=0)||(i%2!=0 && j%2==0)) res-=vd; else res+=vd; break; case HV_DESCR_DOTS: i=ii<0?-ii:ii; j=jj<0?-jj:jj; if ((i+j)%2==0) res-=vd; else res+=vd; break; default: res+=vd; break; } } return res; } void mask(const hvPictRGB<T> &p, T scal, int size, hvPictMask mm, double norm) { this->reset(p.sizeX(), p.sizeY(), hvColRGB<T>(0)); int i,j; for (i=0;i<this->sizeX(); i++) for (j=0; j<this->sizeY(); j++) { hvVec3<double> res=p.maskPixel(scal,size,i,j,mm); res.scale(1.0/norm); res.abs(); this->update(i,j,hvColRGB<T>((T)(res.X()*(double)scal),(T)(res.Y()*(double)scal),(T)(res.Z()*(double)scal))); } } void erase(const hvBitmap &mm, const hvColRGB<T> &vv) { int i,j; for (i=0;i<this->sizeX(); i++) for (j=0; j<this->sizeY(); j++) { if (!mm.get(i,j)) this->update(i,j,vv); } } void edge(const hvPictRGB<T> &p, T scal, int size) { this->reset(p.sizeX(), p.sizeY(), hvColRGB<T>(0)); int i,j; for (i=0;i<this->sizeX(); i++) for (j=0; j<this->sizeY(); j++) { hvVec3<double> vert=p.maskPixel(scal,size,i,j,HV_EDGE_VERT); hvVec3<double> horiz=p.maskPixel(scal,size,i,j,HV_EDGE_HORIZ); hvVec3<double> diag1=p.maskPixel(scal,size,i,j,HV_EDGE_DIAG1); hvVec3<double> diag2=p.maskPixel(scal,size,i,j,HV_EDGE_DIAG2); vert.scale(1.0/(double)(size*(size*2+1))); vert.abs(); horiz.scale(1.0/(double)(size*(size*2+1))); horiz.abs(); diag1.scale(1.0/(double)(size*(size*2+1))); diag1.abs(); diag2.scale(1.0/(double)(size*(size*2+1))); diag2.abs(); vert.keepMax(vert, horiz); vert.keepMax(vert, diag1); vert.keepMax(vert, diag2); this->update(i,j,hvColRGB<T>((T)(vert.X()*(double)scal),(T)(vert.Y()*(double)scal),(T)(vert.Z()*(double)scal))); } } void discont(const hvPictRGB<T> &p, const hvColRGB<T> c1, const hvColRGB<T> c2) { this->reset(p.sizeX(), p.sizeY(), hvColRGB<T>(0)); int i,j,ii,jj; for (i=0;i<this->sizeX(); i++) for (j=0; j<this->sizeY(); j++) { hvColRGB<T> cc = p.get(i,j); bool eq=true; for (ii=-1; ii<=1;ii++) for (jj=-1; jj<=1; jj++) { int x = i+ii, y = j+jj; if (x<0) x+= this->sizeX(); x %= this->sizeX(); if (y<0) y+= this->sizeY(); y %= this->sizeY(); if (!cc.equals(p.get(x,y))) eq=false; } this->update(i,j,eq?c1:c2); } } hvColRGB<T> avg() const { int i,j; double vr=0.0, vg=0.0, vb=0.0; for (i=0;i<this->sizeX(); i++) for (j=0; j<this->sizeY(); j++) { hvColRGB<T> v = this->get(i,j); vr+=(double)v.RED(); vg+=(double)v.GREEN(); vb+=(double)v.BLUE(); } return hvColRGB<T>((T)(vr/(double)(this->sizeX()*this->sizeY())),(T)(vg/(double)(this->sizeX()*this->sizeY())),(T)(vb/(double)(this->sizeX()*this->sizeY())) ) ; } hvColRGB<T> avg(const hvBitmap &bm) const { int i,j,n=0; double vr=0.0, vg=0.0, vb=0.0; for (i=0;i<this->sizeX(); i++) for (j=0; j<this->sizeY(); j++) { if (bm.get(i,j)) { hvColRGB<T> v = this->get(i,j); vr+=(double)v.RED(); vg+=(double)v.GREEN(); vb+=(double)v.BLUE(); n++; } } return hvColRGB<T>((T)(vr/(double)(n)),(T)(vg/(double)(n)),(T)(vb/(double)(n)) ) ; } void gammaNormalizedMax(T scal, double power) { int i,j; hvColRGB<T> min,max; this->minmax(min,max); printf("Max %d,%d,%d\n", max.RED(), max.GREEN(), max.BLUE()); for (i=0;i<this->sizeX(); i++) for (j=0; j<this->sizeY(); j++) { hvColRGB<T> v = this->get(i,j); v.gammaNormalizedMax(max,scal, power); this->update(i,j,v); } } void gammaClampedMax(T scal, double thresh) { int i, j; hvColRGB<T> min, max; this->minmax(min, max); printf("Max %d,%d,%d\n", max.RED(), max.GREEN(), max.BLUE()); for (i = 0; i<this->sizeX(); i++) for (j = 0; j<this->sizeY(); j++) { hvColRGB<T> v = this->get(i, j); v.gammaClampedMax(max, scal, thresh); this->update(i, j, v); } } void minmax(hvColRGB<T> &min, hvColRGB<T> &max) { int i,j; for (i=0;i<this->sizeX(); i++) for (j=0; j<this->sizeY(); j++) { hvColRGB<T> v = this->get(i,j); if (i==0 && j==0) { min=v; max=v; } min.keepMin(min,v); max.keepMax(max,v); } } void normalize(const hvColRGB<T> &min, const hvColRGB<T> &max, double scal) { int i,j; for (i=0;i<this->sizeX(); i++) for (j=0; j<this->sizeY(); j++) { hvColRGB<T> v = this->get(i,j); v.normalize(min,max, scal); this->update(i,j,v); } } void luminance(T scal, double factor) { int i,j; for (i=0;i<this->sizeX(); i++) for (j=0; j<this->sizeY(); j++) { hvColRGB<T> v = this->get(i,j); double rr=(double)v.RED()*factor; if (rr>(double)scal) rr=(double)scal; double gg=(double)v.GREEN()*factor; if (gg>(double)scal) gg=(double)scal; double bb=(double)v.BLUE()*factor; if (bb>(double)scal) bb=(double)scal; this->update(i,j,hvColRGB<T>(T((rr+gg+bb)/3.0))); } } void scale(T scal, double factor) { int i,j; for (i=0;i<this->sizeX(); i++) for (j=0; j<this->sizeY(); j++) { hvColRGB<T> v = this->get(i,j); double rr=(double)v.RED()*factor; if (rr>(double)scal) rr=(double)scal; double gg=(double)v.GREEN()*factor; if (gg>(double)scal) gg=(double)scal; double bb=(double)v.BLUE()*factor; if (bb>(double)scal) bb=(double)scal; this->update(i,j,hvColRGB<T>(T(rr),T(gg),T(bb))); } } template <class X> void scale(T scal, const hvPict<X> &sc, double norm) { int i,j; for (i=0;i<this->sizeX(); i++) for (j=0; j<this->sizeY(); j++) { hvColRGB<T> v = this->get(i,j); double factor = (double)sc.get(i,j)/norm; double rr=(double)v.RED()*factor; if (rr>(double)scal) rr=(double)scal; double gg=(double)v.GREEN()*factor; if (gg>(double)scal) gg=(double)scal; double bb=(double)v.BLUE()*factor; if (bb>(double)scal) bb=(double)scal; this->update(i,j,hvColRGB<T>(T(rr),T(gg),T(bb))); } } void step(T scal, T ss) { int i,j; for (i=0;i<this->sizeX(); i++) for (j=0; j<this->sizeY(); j++) { hvColRGB<T> v = this->get(i,j); this->update(i,j,hvColRGB<T>(v.RED()<ss?0:scal, v.GREEN()<ss?0:scal, v.BLUE()<ss?0:scal)); } } void drawRect(int px, int py, int sx, int sy, hvColRGB<T> v) { int i,j; for (i=px; i<px+sx; i++) for (j=py; j<py+sy; j++) { if (i>=0 && i<this->sizeX() && j>=0 && j<this->sizeY()) this->update(i,j,v); } } void drawRectBlend(int px, int py, int sx, int sy, hvColRGB<T> v, double alpha) { int i,j; for (i=px; i<px+sx; i++) for (j=py; j<py+sy; j++) { hvColRGB<unsigned char> cc; cc.blend(v,this->get(i,j),alpha); if (i>=0 && i<this->sizeX() && j>=0 && j<this->sizeY()) this->update(i,j,cc); } } void copy(int x, int y, const hvPictRGB<T> &pict) { int i,j; for (i=0; i<pict.sizeX(); i++) for (j=0; j<pict.sizeY(); j++) { this->update(x+i,y+j,pict.get(i,j)); } } void copyRect(int px, int py, int x, int y, int sx, int sy, const hvPictRGB<T> &pict, const hvBitmap &mask) { int i,j; for (i=0; i<sx; i++) for (j=0; j<sy; j++) { if (mask.get(x+i, y+j)) { if (px+i>=0 && px+i<this->sizeX() && py+j>=0 && py+j<this->sizeY()) this->update(px+i,py+j,pict.get(x+i,y+j)); } } } void copyRect(int px, int py, int x, int y, int sx, int sy, const hvPictRGB<T> &pict) { int i,j; for (i=0; i<sx; i++) for (j=0; j<sy; j++) { if (px+i>=0 && px+i<this->sizeX() && py+j>=0 && py+j<this->sizeY()) this->update(px+i,py+j,pict.get(x+i,y+j)); } } void copyRect(int px, int py, int x, int y, int sx, int sy, const hvPictRGB<T> &pict, hvColRGB<unsigned char> col, int dd=2, int bscale=1) { int i,j; for (i=0; i<sx; i++) for (j=0; j<sy; j++) { if (px+i>=0 && px+i<this->sizeX() && py+j>=0 && py+j<this->sizeY()) { if (i<=dd || j<=dd || i>=sx-1-dd || j>=sy-1-dd) this->update(px+i,py+j,col); else this->update(px+i,py+j,pict.get(x+i*bscale,y+j*bscale)); } } } void copyRectShadow(int px, int py, int x, int y, int sx, int sy, const hvPictRGB<T> &pict, hvColRGB<T> col, int hh) { int i,j; for (i=0; i<sx; i++) for (j=0; j<sy; j++) { if (px+i>=0 && px+i<this->sizeX() && py+j>=0 && py+j<this->sizeY()) { if (i==0 || j==0 || i==sx-1 || j==sy-1) this->update(px+i,py+j,col); else this->update(px+i,py+j,pict.get(x+i,y+j)); } } for (i=0; i<sx; i++) for (j=1; j<=hh; j++) { if (px+i+j>=0 && px+i+j<this->sizeX() && py-j>=0 && py-j<this->sizeY()) { hvColRGB<T> cc = this->get(px+i+j,py-j); cc.scale(1.0-(double)j/(double)(hh+1)); this->update(px+i+j,py-j,cc); } } } double minShift(double scale, const hvPictRGB<T> &pi, int posx, int posy, int deltax, int deltay, int &minx, int &miny) { minx=0; miny=0; double minv=1000000.0; int i,j; for (i=-deltax; i<=deltax; i++) for (j=-deltay; j<=deltay; j++) { hvColRGB<double> rr; this->squareDifference(scale,this->sizeX()/2-posx, this->sizeY()/2-posy,pi.sizeX()/2-posx+i,pi.sizeY()/2-posy+j,10,10,pi,rr); double vv = rr.RED()+rr.GREEN()+rr.BLUE(); if (vv<minv) { minx=i, miny=j; minv=vv; } } return minv; } void apply(T scal, const hvLinearTransform3<double> &t) { int i,j; for (i=0;i<this->sizeX(); i++) for (j=0; j<this->sizeY(); j++) { hvColRGB<T> v = this->get(i,j); hvVec3<double> col((double)v.RED()/(double)scal, (double)v.GREEN()/(double)scal,(double)v.BLUE()/(double)scal); col = t.apply(col); v=hvColRGB<T>((T)(col.X()*(double)scal),(T)(col.Y()*(double)scal),(T)(col.Z()*(double)scal)); this->update(i,j,v); } } void applyinverse(T scal, const hvFrame3<double> &fr, double offset, double rescal) { hvLinearTransform3<double> t(fr); int i,j; for (i=0;i<this->sizeX(); i++) for (j=0; j<this->sizeY(); j++) { hvColRGB<T> v = this->get(i,j); hvVec3<double> col(((double)v.RED()/(double)scal-offset)/rescal, ((double)v.GREEN()/(double)scal-offset)/rescal,((double)v.BLUE()/(double)scal-offset)/rescal); col = t.apply(col); v=hvColRGB<T>((T)(col.X()*(double)scal),(T)(col.Y()*(double)scal),(T)(col.Z()*(double)scal)); this->update(i,j,v); } } void apply(T scal, const hvFrame3<double> &fr, double offset, double rescal) { hvLinearTransform3<double> t; t.inverseFrame3(fr); int i,j; for (i=0;i<this->sizeX(); i++) for (j=0; j<this->sizeY(); j++) { hvColRGB<T> v = this->get(i,j); hvVec3<double> col((double)v.RED()/(double)scal, (double)v.GREEN()/(double)scal,(double)v.BLUE()/(double)scal); col = t.apply(col); double rr = (col.X()*rescal+offset); if (rr<0.0) rr=0.0; else if (rr>1.0) rr=1.0; double gg = (col.Y()*rescal+offset); if (gg<0.0) gg=0.0; else if (gg>1.0) gg=1.0; double bb = (col.Z()*rescal+offset); if (bb<0.0) bb=0.0; else if (bb>1.0) bb=1.0; v=hvColRGB<T>((T)(rr*(double)scal),(T)(gg*(double)scal),(T)(bb*(double)scal)); this->update(i,j,v); } } hvFrame3<double> pca(T scal, hvBitmap *mask=0) const { int i,j; hvVec3<double> sum; int npix=0; /*** computing mean value ***/ for (i=0;i<this->sizeX(); i++) for (j=0; j<this->sizeY(); j++) { hvColRGB<T> v = this->get(i,j); hvVec3<double> col; bool ok=true; if (mask!=0) ok = mask->get(i,j); if (ok) { npix++; col = hvVec3<double>((double)v.RED()/(double)scal, (double)v.GREEN()/(double)scal,(double)v.BLUE()/(double)scal); sum += col; } } sum /= (double)(npix); /*** computing Covariance matrix covar ***/ hvMat3<double> covar; for (i=0;i<this->sizeX(); i++) for (j=0; j<this->sizeY(); j++) { bool ok=true; if (mask!=0) ok = mask->get(i,j); if (ok) { hvColRGB<T> v = this->get(i,j); hvVec3<double> col((double)v.RED()/(double)scal, (double)v.GREEN()/(double)scal,(double)v.BLUE()/(double)scal); col -= sum; covar += hvMat3<double>( hvVec3<double>(col.X()*col.X(), col.X()*col.Y(), col.X()*col.Z()), hvVec3<double>(col.Y()*col.X(), col.Y()*col.Y(), col.Y()*col.Z()), hvVec3<double>(col.Z()*col.X(), col.Z()*col.Y(), col.Z()*col.Z()) ); } } hvMat3<double> rr = covar.eigen(); return hvFrame3<double>(sum, rr); } static void readPPMLine(FILE *fd, char buff[256]) { do { fgets(buff,255,fd); } while(buff[0]=='#'); } void loadPPM(FILE *fd, T norm) { int sx, sy; int i,j, type; char buff[256]; hvColRGB<T> co; readPPMLine(fd,buff); if (strcmp(buff,"P6\n")==0) type = 0; else if (strcmp(buff,"P3\n")==0) type = 1; else { type = 2; printf("unknown picture PPM type=%d (%s)\n", type,buff); } readPPMLine(fd,buff); sscanf(buff,"%d %d",&sx,&sy); readPPMLine(fd,buff); if (strcmp(buff,"255\n")!=0){ printf("type=%d\n", type); reset(); } reset(sx, sy, hvColRGB<T>()); for (i=0; i<sy; i++) for (j=0; j<sx; j++) { unsigned char r,g,b; if (type==0) { fread(&r,1,sizeof(unsigned char),fd); fread(&g,1,sizeof(unsigned char),fd); fread(&b,1,sizeof(unsigned char),fd); } else if (type==1) { int rr, gg, bb; fscanf(fd, "%d %d %d", &rr, &gg, &bb); r= (unsigned char)rr; g= (unsigned char)gg; b= (unsigned char)bb; } else { r=0; g=0; b=0; } hvArray2< hvColRGB<T> >::update(j,sy-i-1,hvColRGB<T>((T)r/norm, (T)g/norm, (T)b/norm)); } } void savePPM(FILE *fd, T norm) { int i,j; hvColRGB<T> co; unsigned char v; fprintf(fd,"P6\n"); fprintf(fd,"%d %d\n",this->sizeX(),this->sizeY()); fprintf(fd,"255\n"); for (i=0; i<this->sizeY(); i++) for (j=0; j<this->sizeX(); j++) { co = hvArray2< hvColRGB<T> >::get(j, this->sizeY()-i-1); v = (unsigned char)((T)co.RED()*norm); fwrite(&v,1,sizeof(unsigned char),fd); v = (unsigned char)((T)co.GREEN()*norm); fwrite(&v,1,sizeof(unsigned char),fd); v = (unsigned char)((T)co.BLUE()*norm); fwrite(&v,1,sizeof(unsigned char),fd); } } static void RGBE_WriteHeader(FILE *fp, int width, int height, rgbe_header_info *info) { char *programtype = "RGBE"; if (info && (info->valid & RGBE_VALID_PROGRAMTYPE)) programtype = info->programtype; fprintf(fp,"#?%s\n",programtype); if (info && (info->valid & RGBE_VALID_GAMMA)) { fprintf(fp,"GAMMA=%g\n",info->gamma); } if (info && (info->valid & RGBE_VALID_EXPOSURE)) { fprintf(fp,"EXPOSURE=%g\n",info->exposure); } fprintf(fp,"FORMAT=32-bit_rle_rgbe\n\n"); fprintf(fp, "-Y %d +X %d\n", height, width); } bool RGBE_ReadHeader(FILE *fp, int *width, int *height, rgbe_header_info *info) { char buf[256]; int found_format; float tempf; int i; found_format = 0; if (info) { info->valid = 0; info->programtype[0] = 0; info->gamma = 1.0; info->exposure = 1.0; } else hvFatal("no rgbe_header_info pointer given"); if (fgets(buf,256,fp) == 0) return false; if ((buf[0] != '#')||(buf[1] != '?')) return false; info->valid |= RGBE_VALID_PROGRAMTYPE; for(i=0;i<sizeof(info->programtype)-1;i++) { if ((buf[i+2] == 0) || buf[i+2]==' ') break; info->programtype[i] = buf[i+2]; } info->programtype[i] = 0; bool cont=true; while(cont) { if (fgets(buf,256,fp) == 0) return false; if (strcmp(buf,"FORMAT=32-bit_rle_rgbe\n") == 0) { } else if (sscanf(buf,"GAMMA=%g",&tempf) == 1) { info->gamma = tempf; info->valid |= RGBE_VALID_GAMMA; } else if (sscanf(buf,"EXPOSURE=%g",&tempf) == 1) { info->exposure = tempf; info->valid |= RGBE_VALID_EXPOSURE; } else if (sscanf(buf,"-Y %d +X %d",height,width) == 2) cont=false; //if (cont) if (fgets(buf,256,fp) == 0) return false; } return true; } void RGBE_WritePixels(FILE *fp, T norm) { unsigned char rgbe[4]; int i,j; hvColRGB<T> co; unsigned char v; for (i=0; i<this->sizeY(); i++) for (j=0; j<this->sizeX(); j++) { co = hvArray2< hvColRGB<T> >::get(j, this->sizeY()-i-1); co.torgbe(norm, rgbe); fwrite(rgbe, 4, 1, fp); } } bool RGBE_ReadPixels_RLE(FILE *fp, T norm, int scanline_width, int num_scanlines) { unsigned char rgbe[4], *scanline_buffer, *ptr, *ptr_end; int i, count; unsigned char buf[2]; if ((scanline_width < 8)||(scanline_width > 0x7fff)) { printf("not RLE encoded\n"); return false; } //RGBE_ReadPixels(fp,data,scanline_width*num_scanlines); reset(scanline_width, num_scanlines, hvColRGB<T>()); scanline_buffer = 0; /* read in each successive scanline */ while(num_scanlines > 0) { if (fread(rgbe,sizeof(rgbe),1,fp) < 1) { printf("file corrupt in line %d\n",num_scanlines); if (scanline_buffer!=0) free(scanline_buffer); return false; } if ((rgbe[0] != 2)||(rgbe[1] != 2)||(rgbe[2] & 0x80)) { printf("file is not run length encoded in line %d\n",num_scanlines); /* this file is not run length encoded */ //rgbe2float(&data[0],&data[1],&data[2],rgbe); //data += RGBE_DATA_SIZE; if (scanline_buffer!=0) free(scanline_buffer); return false; //RGBE_ReadPixels(fp,data,scanline_width*num_scanlines-1); } if ((((int)rgbe[2])<<8 | rgbe[3]) != scanline_width) { if (scanline_buffer!=0) free(scanline_buffer); printf("wrong scanline width in line %d\n",num_scanlines); return false; } if (scanline_buffer == 0) scanline_buffer = (unsigned char *)malloc(sizeof(unsigned char)*4*scanline_width); ptr = &scanline_buffer[0]; /* read each of the four channels for the scanline into the buffer */ for(i=0;i<4;i++) { ptr_end = &scanline_buffer[(i+1)*scanline_width]; while(ptr < ptr_end) { if (fread(buf,sizeof(buf[0])*2,1,fp) < 1) { free(scanline_buffer); printf("file corrupt\n"); return false; } if (buf[0] > 128) { /* a run of the same value */ count = buf[0]-128; if ((count == 0)||(count > ptr_end - ptr)) { free(scanline_buffer); printf("bad scanline data"); return false; } while(count-- > 0) *ptr++ = buf[1]; } else { /* a non-run */ count = buf[0]; if ((count == 0)||(count > ptr_end - ptr)) { free(scanline_buffer); printf("bad scanline data"); return false; } *ptr++ = buf[1]; if (--count > 0) { if (fread(ptr,sizeof(*ptr)*count,1,fp) < 1) { free(scanline_buffer); printf("file corrupt\n"); return false; } ptr += count; } } } } /* now convert data from buffer into floats */ for(i=0;i<scanline_width;i++) { rgbe[0] = scanline_buffer[i]; rgbe[1] = scanline_buffer[i+scanline_width]; rgbe[2] = scanline_buffer[i+2*scanline_width]; rgbe[3] = scanline_buffer[i+3*scanline_width]; hvColRGB<T> col; col.fromrgbe(norm, rgbe); hvArray2< hvColRGB<T> >::update(i, num_scanlines-1, col); } num_scanlines--; } free(scanline_buffer); return true; } /****************************************************************************** * neighborMatchBlocErrorV2() ******************************************************************************/ double neighborMatchBlocErrorV2( const hvBitmap &yet, int i, int j, // exemplar coordinate float indweight, const hvPict<unsigned char> &labels, // guidance labels double scale, // normalization factor for data (ex: 255 to work with uchar data from [0;255] to [0;1]) int bsize, const hvBitmap &wmask, // guidance mask const hvPictRGB<unsigned char> &ex, const hvPict<unsigned char> &exlabel, // exemplar colors and labels int x, int y ) // block coordinate { int ii, jj; // counter of "processed" pixels in block int count = 0; // Initialize block error double err = 0.0; // Iterate through block for ( jj = 0; jj < bsize; jj++ ) { for ( ii = 0; ii < bsize ; ii ++ ) { int px = ii; int py = jj; // check bounds if ( x + px >= wmask.sizeX() ) px = wmask.sizeX() - 1 - x; if ( y + py >= wmask.sizeY() ) py = wmask.sizeY() - 1 - y; // only if in mask if ( !yet.get( x + px, y + py ) && wmask.get( x + px, y + py ) ) { // Compute distance error double r, g, b; // - guidance hvColRGB<unsigned char> col = this->get(x + px, y + py); r = (double)col.RED() / scale; g = (double)col.GREEN() / scale; b = (double)col.BLUE() / scale; // - exemplar hvColRGB<unsigned char> cole = ex.get(i + px, j + py); // - error (L2) r = r - (double)cole.RED() / scale; g = g - (double)cole.GREEN() / scale; b = b - (double)cole.BLUE() / scale; err += r*r + g*g + b*b; // Compute label error // - guidance unsigned char ind = labels.get(x + px, y + py); // - exemplar unsigned char inde = exlabel.get(i + px, j + py); // - error if ( ind != inde ) { // add a user given penalty err += indweight; } // Update counter (processed pixels) count++; } } } if ( count == 0 ) { // retrun a max error err = 255.0; #if 1 // DEBUG printf( "\nneighborMatchBlocErrorV2(): count=0 => err=255" ); #endif } else { // Normalize error err /= (double)count; } return err; } /****************************************************************************** * Use a random walk like strategy to find best match * * - best candidate will be returned in (rx,ry) ******************************************************************************/ double bestNeighborMatchBlocV2( const hvBitmap &yet, hvBitmap &keepit, const float MERR, // per-pixel threshold error in a block to keep it or not const int shiftx, const int shifty, const float indweight, const hvPict<unsigned char> &labels, const double scale, // normalization error const int bsize, // block size const int factor, // unused parameter const hvBitmap &wmask, const hvPictRGB<unsigned char> &ex, const hvPict<unsigned char> &exlabel, const int x, const int y, int &rx, int &ry, float rnd = 1.0 ) { int i, j, k, ii, jj; // Initialize PRNG (per block) unsigned int seed; hvNoise::seeding( shiftx + x, shifty + y, 2, seed ); double errmin = -1.0; //rx = 0; ry = 0; int pcount = 0; // vector of random sample points std::vector<int> ppi, ppj; ppi.reserve( 10 ); ppj.reserve( 10 ); // Initialize first sample // - x int rposx = (int)( (double)( ex.sizeX() - 2 ) * ( 1.0 - rnd ) ); if ( rposx < 1 ) rposx = 1; // - y int rposy = (int)( (double)( ex.sizeY() - 2 ) * ( 1.0 - rnd ) ); if ( rposy < 1 ) rposy = 1; int count = 0; for (i = 0; i < bsize; i++) for (j = 0; j < bsize; j++) if ( yet.get( x + i, y + j ) ) count++; if ( count == bsize * bsize ) { return 0.0; } //if (!first) //{ // double err = neighborMatchBlocErrorV2(rx, ry, indweight, labels, scale, bsize, wmask, ex, exlabel, x, y); // if (err <= MERR) // { // printf("keep %d,%d=>%d,%d, err=%g\n", x, y, rx, ry, err); // return err; // } //} // Sample exemplar coordinates uniformly for ( i = 0; i < ex.sizeX() - bsize - 3*rposx/2 - 1; i += rposx ) for ( j = 0; j < ex.sizeY() - bsize -3*rposy/2 - 1; j += rposy ) { ppi.push_back( i ); ppj.push_back( j ); pcount++; ppi.push_back( i + rposx/2 ); ppj.push_back( j + rposy/2 ); pcount++; } // Handle error if ( ppi.empty() || ppj.empty() ) { printf( "\nERROR: no sample point in bestNeighborMatchBloc !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" ); assert( false ); return 1.0; // TODO: which value to return? } // Shuffle coordinates // TODO : size of list divided by 2 (or less, ex: > 1/4) for ( k = 0; k < 200; k++) // number of passes of shuffle { int ind1 = (int)((0.5*hvNoise::next(seed)+0.5)*(double)(pcount)); if ( ind1 >= pcount ) ind1 = pcount - 1; ind1 = std::max( 0, ind1 ); int ind2 = (int)((0.5*hvNoise::next(seed) + 0.5)*(double)(pcount)); if ( ind2 >= pcount ) ind2 = pcount - 1; ind2 = std::max( 0, ind1 ); rx = ppi[ ind1 ]; ry = ppj[ ind1 ]; ppi[ ind1 ] = ppi[ ind2 ]; ppj[ ind1 ] = ppj[ ind2 ]; ppi[ ind2 ] = rx; ppj[ ind2 ] = ry; } // Iterate through candidate samples and sample1 point around randomly for ( k = 0; k < pcount; k++ ) { double fact = 0.75*hvNoise::next( seed ) + 0.75; // Sample new candidate inside a radius from candidate i = ppi[ k ]; j = ppj[ k ]; int decalx = (int)( ( 0.5 * hvNoise::next( seed ) + 0.5 ) * (double)( rposx ) ); int decaly = (int)( ( 0.5 * hvNoise::next( seed ) + 0.5 ) * (double)( rposy ) ); // - compute block error (MSE) double err = neighborMatchBlocErrorV2( yet, i + decalx, j + decaly, indweight, labels, scale, bsize, wmask, ex, exlabel, x, y ); // Update best candidate info //if (err==0.0) err = 1.0 / 255.0*(double)rand() / (double)RAND_MAX; if (errmin == -1.0) { errmin = err; rx = i + decalx; ry = j + decaly; } //else if (errmin>err && err<fact*MERR) { errmin = err; rx = i + decalx; ry = j + decaly; } else if (errmin>err) { errmin = err; rx = i + decalx; ry = j + decaly; } //printf("pixel %d,%d, pos %d,%d -> err=%g (min=%g)\n", x, y, rx, ry, err, errmin); } // Iterate through best candidate block // to update map telling whether or not to keep its pixels according to a per-pixel threshold error for ( i = 0; i < bsize; i++ ) for ( j = 0; j < bsize; j++ ) if ( !yet.get( x + i, y + j ) ) { // - compute block error (MSE) => per pixel (see: 1/*block size*/) double err = neighborMatchBlocErrorV2( yet, rx+i, ry+j, indweight, labels, scale, 1/*block size*/, wmask, ex, exlabel, x+i, y+j ); // Update "keep" map keepit.set( i, j, err <= MERR ); } //if (!first) printf("modified %d,%d=>%d,%d, err=%g\n", x, y, rx, ry, errmin); // Return best block error return errmin; } // Use a random walk like strategy to find best match based on a distance / feature image void refineBestNeighborMatchwdist(hvPictRGB<unsigned char> &thisdist, const hvPictRGB<unsigned char> &ex, const hvPictRGB<unsigned char> &exdist, double weight, int x, int y, int neighbor, int ix[], int iy[], int nn, int &rx, int &ry, int SX = 0, int SY = 0, int DX = 0, int DY = 0) { const int NSAMPLES = 5; const int DEPTH = 3; if (SX == 0) { SX = ex.sizeX(); } if (SY == 0) { SY = ex.sizeY(); } int RADIUS = 5 * neighbor; if (RADIUS < 1) RADIUS = 1; int i, j, k; double minerr, searcherr, besterr; int spx, spy, bestx, besty; for (i = 0; i < nn; i++) { int deltax = ix[i] / SX, deltay = iy[i] / SY; for (j = 0; j < NSAMPLES; j++) // first level is random { int px = ix[i] - deltax*SX - RADIUS + (int)(2.0*(double)rand() / (double)RAND_MAX*(double)RADIUS); if (px < neighbor) px = neighbor; if (px >= SX - neighbor) px = SX - neighbor - 1; int py = iy[i] - deltay*SY - RADIUS + (int)(2.0*(double)rand() / (double)RAND_MAX*(double)RADIUS); if (py < neighbor) py = neighbor; if (py >= SY - neighbor) py = SY - neighbor - 1; px += SX*deltax; py += SY*deltay; if (px < neighbor) px = neighbor; if (py < neighbor) py = neighbor; if (px >= this->sizeX() - neighbor) px = this->sizeX() - neighbor - 1; if (py >= this->sizeY() - neighbor) py = this->sizeY() - neighbor - 1; double err = this->meanSquareDifference(ex, 255.0, x, y, px, py, neighbor)*(1.0 - weight) + thisdist.meanSquareDifference(exdist, 255.0, x, y, px, py, neighbor)*weight; if (j == 0) { searcherr = err; spx = px; spy = py; } else if (err < searcherr) { searcherr = err; spx = px; spy = py; } } minerr = searcherr; bestx = spx; besty = spy; //printf("i=%d, %d,%d (neigh=%d, S %d,%d, delta %d,%d\n", i, bestx, besty,neighbor,SX,SY,deltax,deltay); RADIUS /= 2; if (RADIUS < 1) RADIUS = 1; for (k = 0; k < DEPTH && RADIUS>1; k++) { int deltax = bestx / SX, deltay = besty / SY; for (j = 0; j < NSAMPLES; j++) // next levels are closer and closer to previous best { int px = bestx - deltax*SX - RADIUS + (int)(2.0*(double)rand() / (double)RAND_MAX*(double)RADIUS); if (px < neighbor) px = neighbor; if (px >= SX - neighbor) px = SX - neighbor - 1; int py = besty - deltay*SY - RADIUS + (int)(2.0*(double)rand() / (double)RAND_MAX*(double)RADIUS); if (py < neighbor) py = neighbor; if (py >= SY - neighbor) py = SY - neighbor - 1; px += SX*deltax; py += SY*deltay; if (px < neighbor) px = neighbor; if (py < neighbor) py = neighbor; if (px >= this->sizeX() - neighbor) px = this->sizeX() - neighbor - 1; if (py >= this->sizeY() - neighbor) py = this->sizeY() - neighbor - 1; //double err = this->meanSquareDifference(ex, 255.0, x, y, px, py, neighbor); double err = this->meanSquareDifference(ex, 255.0, x, y, px, py, neighbor)*(1.0 - weight) + thisdist.meanSquareDifference(exdist, 255.0, x, y, px, py, neighbor)*weight; if (err < searcherr) { searcherr = err; spx = px; spy = py; } } if (searcherr < minerr) { minerr = searcherr; bestx = spx; besty = spy; } RADIUS /= 2; if (RADIUS < 1) RADIUS = 1; } if (i == 0) { besterr = minerr; rx = bestx; ry = besty; } else if (besterr > minerr) { besterr = minerr; rx = bestx; ry = besty; } //printf("i=%d, best = %d,%d\n", i, rx, ry); } } // Use a random walk like strategy to find best match based on a distance / feature image and guidance map inline bool keepit(int px, int py, const int excludex[], const int excludey[], int nex) { if (nex == 0) return true; for (int i = 0; i < nex; i++) if (px == excludex[i] && py == excludey[i]) return false; return true; } /****************************************************************************** * refineBestNeighborMatchwdistguidanceV2 * * Refine candidate (look for a better one and store its exemplar's position in (px,py) ******************************************************************************/ void refineBestNeighborMatchwdistguidanceV2( int shiftx, int shifty, float indweight, int NSAMPLES, const hvPictRGB<unsigned char> &thisdist, const hvPict<unsigned char> &thislabels, const hvPictRGB<unsigned char> &ex, const hvPictRGB<unsigned char> &exdist, const hvPict<unsigned char> &exlabels, const hvPictRGB<unsigned char> &guidance, const hvPict<unsigned char> &labels, const hvBitmap &mask, double weight, double strength, int x, int y, int neighbor, const int ix[], const int iy[], int nn, int &rx, int &ry, // return best candidate position in exemplar const int excludex[], const int excludey[], int nex ) { unsigned int seed; hvNoise::seeding( shiftx + x, shifty + y, 3, seed ); //const int NSAMPLES = 10; const int DEPTH = 2; int RADIUS = 2 * neighbor; if (RADIUS < 1) RADIUS = 2; int i, j, k; double minerr, searcherr, besterr; int spx, spy, bestx, besty; bool first = true; //--------------------------------------------------------------------- // Search for best candidate //--------------------------------------------------------------------- // Iterate through candidates (ex: 5x5 neighborhoo) // and find best one based on criteria : MSE on small neighborhood (2*neighbor+1) on color, distance and guidance for (i = 0; i < nn; i++) { int px = ix[i]; int py = iy[i]; if ( keepit( px, py, excludex, excludey, nex ) ) { // Compute error on colors, distances and guidance (pptbf + labels + mask) double err = (1.0 - strength) * ( this->meanSquareDifference( ex, 255.0, x, y, px, py, neighbor ) * ( 1.0 - weight ) + thisdist.meanSquareDifference( exdist, 255.0, x, y, px, py, neighbor) * weight ) + strength * guidance.meanSquareDifferenceGuidance( indweight, labels, mask, exdist, exlabels, 255.0, x, y, px, py, neighbor ); // Update best candidate info (error + position) if ( first ) { first = false; besterr = err; rx = px; ry = py; } else if ( !first && err < besterr ) { besterr = err; rx = px; ry = py; } } } //--------------------------------------------------------------------- // Try to find a better candidate by sampling randomly around it (with decreasing radius search) //--------------------------------------------------------------------- // Iterate through candidates (ex: 5x5 neighborhoo) // and find best one based on criteria : MSE on small neighborhood (2*neighbor+1) on color, distance and guidance for ( i = 0; i < nn; i++ ) { // Try to find a better candidate by sampling ramdomly round bool startd = true; while ( startd ) { for ( j = 0; j < NSAMPLES; j++ ) // first level is random { int px = ix[i] - RADIUS + (int)(2.0*(0.5+0.5*hvNoise::next(seed))*(double)RADIUS); if (px < neighbor) px = neighbor; if (px >= ex.sizeX() - neighbor) px = ex.sizeX() - neighbor - 1; int py = iy[i] - RADIUS + (int)(2.0*(0.5 + 0.5*hvNoise::next(seed))*(double)RADIUS); if (py < neighbor) py = neighbor; if (py >= ex.sizeY() - neighbor) py = ex.sizeY() - neighbor - 1; if ( keepit( px, py, excludex, excludey, nex ) ) { double err = (1.0 - strength) * ( this->meanSquareDifference( ex, 255.0, x, y, px, py, neighbor ) * ( 1.0 - weight ) + thisdist.meanSquareDifference(exdist, 255.0, x, y, px, py, neighbor) * weight ) + strength * guidance.meanSquareDifferenceGuidance( indweight, labels, mask, exdist, exlabels, 255.0, x, y, px, py, neighbor ); if (startd) { startd = false; searcherr = err; spx = px; spy = py; } else if (!startd && err < searcherr) { searcherr = err; spx = px; spy = py; } } } if (startd) RADIUS *= 2; } minerr = searcherr; bestx = spx; besty = spy; //printf("i=%d, %d,%d (neigh=%d, S %d,%d, delta %d,%d\n", i, bestx, besty,neighbor,SX,SY,deltax,deltay); // Restart process within a smaller radius search RADIUS /= 2; if (RADIUS < 2) RADIUS = 2; for ( k = 0; k < DEPTH && RADIUS>2; k++ ) { for ( j = 0; j < NSAMPLES; j++ ) // next levels are closer and closer to previous best { int px = bestx - RADIUS + (int)(2.0*(0.5 + 0.5*hvNoise::next(seed))*(double)RADIUS); if (px < neighbor) px = neighbor; if (px >= ex.sizeX() - neighbor) px = ex.sizeX() - neighbor - 1; int py = besty - RADIUS + (int)(2.0*(0.5 + 0.5*hvNoise::next(seed))*(double)RADIUS); if (py < neighbor) py = neighbor; if (py >= ex.sizeY() - neighbor) py = ex.sizeY() - neighbor - 1; //double err = this->meanSquareDifference(ex, 255.0, x, y, px, py, neighbor); if (keepit(px, py, excludex, excludey, nex)) { double err = (1.0 - strength)*(this->meanSquareDifference(ex, 255.0, x, y, px, py, neighbor)*(1.0 - weight) + thisdist.meanSquareDifference(exdist, 255.0, x, y, px, py, neighbor)*weight) + strength*guidance.meanSquareDifferenceGuidance(indweight, labels, mask, exdist, exlabels, 255.0, x, y, px, py, neighbor); if (err < searcherr) { searcherr = err; spx = px; spy = py; } } } if (searcherr < minerr) { minerr = searcherr; bestx = spx; besty = spy; } RADIUS /= 2; if (RADIUS < 1) RADIUS = 1; } //if (i == 0) { besterr = minerr; rx = bestx; ry = besty; } //else if (besterr > minerr) { besterr = minerr; rx = bestx; ry = besty; } //printf("i=%d, best = %d,%d\n", i, rx, ry); } } //////////////////////////////////////////////////////////// // compute square differences //////////////////////////////////////////////////////////// int squareDifference(double scale, int x, int y, int i, int j, int neighbor, const hvBitmap &bseed, const hvBitmap &bm, hvColRGB<double> &res) { int count=0, nx, ny; double errr=0.0, errg=0.0, errb=0.0; for (nx=-neighbor;nx<=neighbor; nx++) for (ny=-neighbor;ny<=neighbor; ny++) { int px, py, epx, epy; px = x+nx; if (px<0) px+=this->sizeX(); else if (px>= this->sizeX()) px-= this->sizeX(); py = y+ny; if (py<0) py+= this->sizeY(); else if (py>= this->sizeY()) py-= this->sizeY(); epx = i+nx; if (epx<0) epx+= this->sizeX(); else if (epx>= this->sizeX()) epx-= this->sizeX(); epy = j+ny; if (epy<0) epy+= this->sizeY(); else if (epy>= this->sizeY()) epy-= this->sizeY(); if (bseed.get(px,py)==true && bm.get(epx, epy)==true) { double r,g,b; hvColRGB<unsigned char> col = this->get(px,py); r = (double)col.RED()/scale; g = (double)col.GREEN()/scale; b = (double)col.BLUE()/scale; col = this->get(epx,epy); r = r - (double)col.RED()/scale; g = g - (double)col.GREEN()/scale; b = b - (double)col.BLUE()/scale; errr += r*r; errg += g*g; errb += b*b; count++; } } res = hvColRGB<double>(errr, errg, errb); return count; } double meanSquareDifference(const hvPictRGB<unsigned char> &ex, double scale, int x, int y, int i, int j, int neighbor) const { int count = 0, nx, ny; double errr = 0.0, errg = 0.0, errb = 0.0; for (nx = -neighbor; nx <= neighbor; nx++) for (ny = -neighbor; ny <= neighbor; ny++) { int px, py, epx, epy; px = x + nx; if (px<0) px += this->sizeX(); else if (px >= this->sizeX()) px -= this->sizeX(); py = y + ny; if (py<0) py += this->sizeY(); else if (py >= this->sizeY()) py -= this->sizeY(); epx = i + nx; if (epx<0) epx += ex.sizeX(); else if (epx >= ex.sizeX()) epx -= ex.sizeX(); epy = j + ny; if (epy<0) epy += ex.sizeY(); else if (epy >= ex.sizeY()) epy -= ex.sizeY(); if (px>=0 && px<this->sizeX() && py >= 0 && py<this->sizeY() && epx>=0 && epx<ex.sizeX() && epy >= 0 && epy<ex.sizeY() ) { double r, g, b; hvColRGB<unsigned char> col = this->get(px, py); r = (double)col.RED() / scale; g = (double)col.GREEN() / scale; b = (double)col.BLUE() / scale; col = ex.get(epx, epy); r = r - (double)col.RED() / scale; g = g - (double)col.GREEN() / scale; b = b - (double)col.BLUE() / scale; errr += r*r; errg += g*g; errb += b*b; count++; } } if (count == 0) hvFatal("could not find neighborhood"); return (errr+errg+errb)/3.0/(double)count; } double meanSquareDifference(const hvBitmap &mask, const hvPictRGB<unsigned char> &ex, double scale, int x, int y, int i, int j, int neighbor) const { int count = 0, nx, ny; double errr = 0.0, errg = 0.0, errb = 0.0; for (nx = -neighbor; nx <= neighbor; nx++) for (ny = -neighbor; ny <= neighbor; ny++) { int px, py, epx, epy; px = x + nx; if (px<0) px += this->sizeX(); else if (px >= this->sizeX()) px -= this->sizeX(); py = y + ny; if (py<0) py += this->sizeY(); else if (py >= this->sizeY()) py -= this->sizeY(); epx = i + nx; if (epx<0) epx += ex.sizeX(); else if (epx >= ex.sizeX()) epx -= ex.sizeX(); epy = j + ny; if (epy<0) epy += ex.sizeY(); else if (epy >= ex.sizeY()) epy -= ex.sizeY(); if (px >= 0 && px<this->sizeX() && py >= 0 && py<this->sizeY() && epx >= 0 && epx<ex.sizeX() && epy >= 0 && epy<ex.sizeY()) { if (mask.get(px, py)) { double r, g, b; hvColRGB<unsigned char> col = this->get(px, py); r = (double)col.RED() / scale; g = (double)col.GREEN() / scale; b = (double)col.BLUE() / scale; col = ex.get(epx, epy); r = r - (double)col.RED() / scale; g = g - (double)col.GREEN() / scale; b = b - (double)col.BLUE() / scale; errr += r*r; errg += g*g; errb += b*b; count++; } } } if (count == 0) return 0.0; return (errr + errg + errb) / 3.0 / (double)count; } double meanSquareDifferenceGuidance(float indweight, const hvPict<unsigned char> &labels, const hvBitmap &mask, const hvPictRGB<unsigned char> &ex, const hvPict<unsigned char> &exlabels, double scale, int x, int y, int i, int j, int neighbor) const { int count = 0, nx, ny; double errr = 0.0, errg = 0.0, errb = 0.0, errl=0.0; for (nx = -neighbor; nx <= neighbor; nx++) for (ny = -neighbor; ny <= neighbor; ny++) { int px, py, epx, epy; px = x + nx; if (px<0) px += this->sizeX(); else if (px >= this->sizeX()) px -= this->sizeX(); py = y + ny; if (py<0) py += this->sizeY(); else if (py >= this->sizeY()) py -= this->sizeY(); epx = i + nx; if (epx<0) epx += ex.sizeX(); else if (epx >= ex.sizeX()) epx -= ex.sizeX(); epy = j + ny; if (epy<0) epy += ex.sizeY(); else if (epy >= ex.sizeY()) epy -= ex.sizeY(); if (px >= 0 && px<this->sizeX() && py >= 0 && py<this->sizeY() && epx >= 0 && epx<ex.sizeX() && epy >= 0 && epy<ex.sizeY()) { if (mask.get(px, py)) { double r, g, b; hvColRGB<unsigned char> col = this->get(px, py); r = (double)col.RED() / scale; g = (double)col.GREEN() / scale; b = (double)col.BLUE() / scale; hvColRGB<unsigned char> cole = ex.get(epx, epy); r = r - (double)cole.RED() / scale; g = g - (double)cole.GREEN() / scale; b = b - (double)cole.BLUE() / scale; errr += r*r; errg += g*g; errb += b*b; if (labels.get(px, py) != exlabels.get(epx,epy)) errl += indweight; count++; } } } if (count == 0) return 0.0; return ((errr + errg + errb ) / 3.0+errl) / (double)count; } int squareDifference(double scale, int x, int y, int i, int j, int neighbor, hvColRGB<double> &res) { int count=0, nx, ny; double errr=0.0, errg=0.0, errb=0.0; for (nx=-neighbor;nx<=neighbor; nx++) for (ny=-neighbor;ny<=neighbor; ny++) { int px, py, epx, epy; px = x+nx; if (px<0) px+= this->sizeX(); else if (px>= this->sizeX()) px-= this->sizeX(); py = y+ny; if (py<0) py+= this->sizeY(); else if (py>= this->sizeY()) py-= this->sizeY(); epx = i+nx; if (epx<0) epx+= this->sizeX(); else if (epx>= this->sizeX()) epx-= this->sizeX(); epy = j+ny; if (epy<0) epy+= this->sizeY(); else if (epy>= this->sizeY()) epy-= this->sizeY(); double r,g,b; hvColRGB<unsigned char> col = this->get(px,py); r = (double)col.RED()/scale; g = (double)col.GREEN()/scale; b = (double)col.BLUE()/scale; col = this->get(epx,epy); r = r - (double)col.RED()/scale; g = g - (double)col.GREEN()/scale; b = b - (double)col.BLUE()/scale; errr += r*r; errg += g*g; errb += b*b; count++; } res = hvColRGB<double>(errr, errg, errb); return count; } void squareDifference(double scale, int px, int py, int x, int y, int sx, int sy, const hvPictRGB<T> &pi, const hvBitmap &mask, hvColRGB<double> &res) { int count=0, i,j; double errr=0.0, errg=0.0, errb=0.0; for (i=0; i<sx;i++) for (j=0; j<sy;j++) { if (mask.get(x+i,y+j)) { double r,g,b; //if (px+i<0 || px+i>=sizeX() || py+j<0 || py+j>=sizeY()) { printf("out of this picture range: %d,%d\n", px+i,py+j); } int ppx=px+i, ppy=py+j; if (ppx<0) ppx+= this->sizeX(); else if (ppx>= this->sizeX()) ppx-= this->sizeX(); if (ppy<0) ppy+= this->sizeY(); else if (ppy>= this->sizeY()) ppy-= this->sizeY(); hvColRGB<unsigned char> col = this->get(ppx,ppy); r = (double)col.RED()/scale; g = (double)col.GREEN()/scale; b = (double)col.BLUE()/scale; //if (x+i<0 || x+i>=pi.sizeX() || y+j<0 || y+j>=pi.sizeY()) { printf("out of pi picture range: %d,%d\n", x+i,y+j); } col = pi.get(x+i,y+j); r = r - (double)col.RED()/scale; g = g - (double)col.GREEN()/scale; b = b - (double)col.BLUE()/scale; errr += r*r; errg += g*g; errb += b*b; } } res = hvColRGB<double>(errr, errg, errb); } void squareDifference(double scale, int px, int py, int x, int y, int sx, int sy, const hvPictRGB<T> &pi, hvColRGB<double> &res, int step=1) { int count=0, i,j; double errr=0.0, errg=0.0, errb=0.0; for (i=0; i<sx;i+=step) for (j=0; j<sy;j+=step) { double r,g,b; //if (px+i<0 || px+i>=sizeX() || py+j<0 || py+j>=sizeY()) { printf("out of this picture range: %d,%d\n", px+i,py+j); } int ppx=px+i, ppy=py+j; if (ppx<0) ppx+= this->sizeX(); else if (ppx>= this->sizeX()) ppx-= this->sizeX(); if (ppy<0) ppy+= this->sizeY(); else if (ppy>= this->sizeY()) ppy-= this->sizeY(); hvColRGB<unsigned char> col = this->get(ppx,ppy); r = (double)col.RED()/scale; g = (double)col.GREEN()/scale; b = (double)col.BLUE()/scale; //if (x+i<0 || x+i>=pi.sizeX() || y+j<0 || y+j>=pi.sizeY()) { printf("out of pi picture range: %d,%d\n", x+i,y+j); } col = pi.get(x+i,y+j); r = r - (double)col.RED()/scale; g = g - (double)col.GREEN()/scale; b = b - (double)col.BLUE()/scale; errr += r*r; errg += g*g; errb += b*b; } res = hvColRGB<double>(errr, errg, errb); } void squareDifferenceBorder(double scale, int px, int py, int x, int y, int sx, int sy, const hvPictRGB<T> &pi, hvColRGB<double> &res, int depth = 1) { int count = 0, i, j; double errr = 0.0, errg = 0.0, errb = 0.0; for (i = 0; i<sx; i += 1) for (j = 0; j<sy; j += 1) { if (i < depth || i >= sx - depth || j < sy || j >= sy - depth) { double r, g, b; //if (px+i<0 || px+i>=sizeX() || py+j<0 || py+j>=sizeY()) { printf("out of this picture range: %d,%d\n", px+i,py+j); } int ppx = px + i, ppy = py + j; if (ppx < 0) ppx += this->sizeX(); else if (ppx >= this->sizeX()) ppx -= this->sizeX(); if (ppy < 0) ppy += this->sizeY(); else if (ppy >= this->sizeY()) ppy -= this->sizeY(); hvColRGB<unsigned char> col = this->get(ppx, ppy); r = (double)col.RED() / scale; g = (double)col.GREEN() / scale; b = (double)col.BLUE() / scale; //if (x+i<0 || x+i>=pi.sizeX() || y+j<0 || y+j>=pi.sizeY()) { printf("out of pi picture range: %d,%d\n", x+i,y+j); } col = pi.get(x + i, y + j); r = r - (double)col.RED() / scale; g = g - (double)col.GREEN() / scale; b = b - (double)col.BLUE() / scale; errr += r*r; errg += g*g; errb += b*b; } } res = hvColRGB<double>(errr, errg, errb); } void weightedSquareDifference(double scale, int px, int py, int x, int y, int sx, int sy, const hvPictRGB<T> &pi, const hvPict<double> &weight, hvColRGB<double> &res) { int count=0, i,j; double errr=0.0, errg=0.0, errb=0.0; for (i=0; i<sx;i++) for (j=0; j<sy;j++) { if (weight.get(x+i,y+j)>0.0) { double r,g,b; double ww = weight.get(x+i,y+j); //if (px+i<0 || px+i>=sizeX() || py+j<0 || py+j>=sizeY()) { printf("out of this picture range: %d,%d\n", px+i,py+j); } int ppx=px+i, ppy=py+j; if (ppx<0) ppx+= this->sizeX(); else if (ppx>= this->sizeX()) ppx-= this->sizeX(); if (ppy<0) ppy+= this->sizeY(); else if (ppy>= this->sizeY()) ppy-= this->sizeY(); hvColRGB<unsigned char> col = this->get(ppx,ppy); r = (double)col.RED()/scale; g = (double)col.GREEN()/scale; b = (double)col.BLUE()/scale; //if (x+i<0 || x+i>=pi.sizeX() || y+j<0 || y+j>=pi.sizeY()) { printf("out of pi picture range: %d,%d\n", x+i,y+j); } col = pi.get(x+i,y+j); r = r - (double)col.RED()/scale; g = g - (double)col.GREEN()/scale; b = b - (double)col.BLUE()/scale; errr += r*r*ww; errg += g*g*ww; errb += b*b*ww; } } res = hvColRGB<double>(errr, errg, errb); } void imagefromindex(const hvPictRGB<T> &example, hvArray2<hvVec2<int> > &index) { this->reset(index.sizeX(), index.sizeY(), hvColRGB<T>()); int i, j; for (i = 0; i < this->sizeX(); i++) for (j = 0; j < this->sizeY(); j++) { hvVec2<int> p = index.get(i, j); this->update(i, j, example.get(p.X(), p.Y())); } } // make gaussian stack void makepyr( const char *name, const hvPictRGB<T> &dist, const hvPict<T> &exlabel, int &s, int &factor, hvPictRGB<T> pyr[10], hvPictRGB<T> pyrdist[10], hvPict<T> pyrlabel[10], int maxs=9) const { char buff[256]; FILE *fd; int ii, jj; s = 0; factor = 1; pyr[0].clone(*this, 0, 0, this->sizeX() - 1, this->sizeY() - 1); pyrdist[0].clone(dist, 0, 0, dist.sizeX() - 1, dist.sizeY() - 1); pyrlabel[0].clone(exlabel, 0, 0, exlabel.sizeX() - 1, exlabel.sizeY() - 1); while (s < maxs && pyr[s].sizeX()>16 && pyr[s].sizeY() > 16) { s++; factor *= 2; pyr[s].shrink(&(pyr[s - 1]), 0); sprintf(buff, "%s_spt_%02d_ex.ppm", name, s); fd = fopen(buff, "wb"); if (fd == 0) { perror("cannot load file:"); } pyr[s].savePPM(fd, 1); fclose(fd); pyrdist[s].shrink(&(pyrdist[s - 1]), 0); sprintf(buff, "%s_spt_%02d_mask.ppm", name, s); fd = fopen(buff, "wb"); if (fd == 0) { perror("cannot load file:"); } pyrdist[s].savePPM(fd, 1); fclose(fd); pyrlabel[s].reset(pyrlabel[s - 1].sizeX()/2, pyrlabel[s - 1].sizeY()/2, 0); for (ii = 0; ii < pyrlabel[s].sizeX(); ii++) for (jj = 0; jj < pyrlabel[s].sizeY(); jj++) { pyrlabel[s].update(ii, jj, pyrlabel[s-1].get(2 * ii, 2 * jj)); } hvPictRGB<unsigned char> labelrgb(pyrlabel[s], 1); sprintf(buff, "%s_spt_%02d_label.ppm", name, s); fd = fopen(buff, "wb"); if (fd == 0) { perror("cannot load file:"); } labelrgb.savePPM(fd, 1); fclose(fd); } } /****************************************************************************** * smartInitialization() ******************************************************************************/ void smartInitialization( const int shiftx, const int shifty, const float MERR, const float indweight, int bb, hvPictRGB<T> &guidance, const hvPict<T> &labels, const hvBitmap &mask, const hvPictRGB<T> &example, const hvPictRGB<T> &distance, const hvPict<T> &exlabels, hvArray2<hvVec2<int> > &index, hvPictRGB<T> &synth, hvPictRGB<T> &synthdist, hvPict<T> &synthlabels ) { int i, j; int rx, ry; printf( "- start smart init box size=%d, at shift %d,%d\n", bb, shiftx, shifty ); // Iterate through scales: from top (fine) to bottom (coarse) // - refining best block candidates accorind to criteria (user provided min/threshold errors on colors, distances, guidance [pptbfn labels]) bool first = true; hvBitmap yet( index.sizeX(), index.sizeY(), false ); do { // Iterate through blocks for ( j = 0; j < index.sizeY(); j += bb ) { for ( i = 0; i < index.sizeX(); i += bb ) { // Per-block bitmap telling whether or not to keep a pixel given its error hvBitmap keepit( bb, bb, false ); //if (!first) //{ // hvVec2<int> pos = index.get(i, j); // rx = pos.X(); // ry = pos.Y(); // //printf("at %d,%d -> %d,%d\n", i, j, rx, ry); //} //else { rx = 0; ry = 0; } // Search for best block (position in [rx,ry]) by sampling blocks in exemplar rx = 0; ry = 0; double err = guidance.bestNeighborMatchBlocV2( yet, keepit, MERR, shiftx, shifty, indweight, labels, 255.0, bb, 2/*unused parameter*/, mask, distance, exlabels, i, j, rx, ry, // returned best candidate coordinate 0.95 ); // Store/write best block data // Iterate through best candidate block for ( int jj = 0; jj < bb; jj++ ) { for ( int ii = 0; ii < bb; ii++ ) { // Check index map bounds if ( i + ii < index.sizeX() && j + jj < index.sizeY() && !yet.get(i+ii,j+jj) && (keepit.get(ii,jj) || bb/2<8) ) { int posx = rx + ii, posy = ry + jj; // Check exemplar bounds if ( posx >= example.sizeX() ) posx = example.sizeX() - 1; if ( posy >= example.sizeY() ) posy = example.sizeY() - 1; // Update index map index.update( i + ii, j + jj, hvVec2<int>(posx, posy) ); // Update synthesized maps (colors, distance, labels) synth.update( i + ii, j + jj, example.get(posx, posy) ); synthdist.update( i + ii, j + jj, distance.get(posx, posy) ); synthlabels.update( i + ii, j + jj, exlabels.get(posx, posy) ); // Update "yet" map yet.set( i + ii, j + jj, true ); } } } } } // Divide block size by 2 (to work on smaller blocks) bb /= 2; // Update flag first = false; } while ( bb >= 4 ); // stop criterion } /****************************************************************************** * Semi-Procedural Texture Synthesis using Point Process Texture Basis Functions. * * Parameter list * GUIDE: pecentage of guidance to relax constraints no borders of structures (1: full constraints; 0: no constrinats) * STRENGTH 0.5 * INITLEVEL 2 * BLOCSIZE 64 * INITERR 100 * INDEXWEIGHT 0 ******************************************************************************/ void execute_semiProceduralTextureSynthesis( // - input texture name const char *name, int STOPATLEVEL, // - position in 2D world space (translation useful when synthesizing tiles of large textures) int posx, int posy, // - input exemplar color and distance map const hvPictRGB<T> &example, const hvPictRGB<T> &exdist, // semi-procedural synthesis parameters double weight, // weight color vs distance (default: 0.8) double powr, // weight to accentuate or diminish guidance (as a power) // label weight float indweight, // half-patch size for neighborhood search int neighbor, // - smart initialization parameters int atlevel, int bsize, float ERR, // - guidance mask, distance and labels const hvBitmap &mask, const hvPictRGB<T> &guidance, // - synthesized 2D uv coordinates hvArray2<hvVec2<int> > &index, const int nbCorrectionPasses, const bool useSmartInitialization ) { // - timer auto startTime = std::chrono::high_resolution_clock::now(); //-------------------------------------- // [stage #1] Preprocessing stage //-------------------------------------- std::cout << "\n[PREPROCESSING stage]\n" << std::endl; //-------------------------------------- // Create pyramid of LOD (level of details): // - input exemplar: color, distance and labels // - guidance: distance (from pptbf), mask (from thresholded pptbf) and labels (from pptbf random values generated at feature points) //-------------------------------------- std::cout << "- build multiscale pyramid" << std::endl; char buff[256]; int i, j, ii, jj; FILE *fd; // - exemplar color, distance, label and guidance distance and labels hvPictRGB<T> pyr[10], synth[10], pyrdist[10], synthdist[10], guid[10], dist; hvPict<unsigned char> pyrlabels[10], labels[10], synthlabels[10], exlabels; // - guidance mask hvBitmap gmask[10]; if (atlevel < 1) atlevel = 1; // Variable of current LOD of the pyramid int s = 0, factor = 1; // Exemplar label and distance pyramids exlabels.reset(exdist.sizeX(), exdist.sizeY(), 0); dist.reset(exdist.sizeX(), exdist.sizeY(), 0); for (ii = 0; ii < dist.sizeX(); ii++) for (jj = 0; jj < dist.sizeY(); jj++) { hvColRGB<unsigned char> col = exdist.get(ii, jj); dist.update(ii, jj, hvColRGB<unsigned char>(col.RED(), col.GREEN(), 0)); exlabels.update(ii, jj, col.BLUE()); } // Exemplar color pyramids example.makepyr( name, dist, exlabels, s, factor, pyr, pyrdist, pyrlabels, atlevel ); // Guidance label and distance pyramids + guidance mask pyramids guid[0].reset(guidance.sizeX(), guidance.sizeY(), hvColRGB<unsigned char>(0)); labels[0].reset(guidance.sizeX(), guidance.sizeY(), 0); for (ii = 0; ii < guid[0].sizeX(); ii++) for (jj = 0; jj < guid[0].sizeY(); jj++) { hvColRGB<unsigned char> col = guidance.get(ii, jj); guid[0].update(ii, jj, hvColRGB<unsigned char>(col.RED(), col.GREEN(), 0)); labels[0].update(ii, jj, col.BLUE()); } gmask[0] = mask; // - iterate over all LOD of the guidance pyramids for (i = 1; i <= s; i++) { guid[i].reset(guid[i - 1].sizeX() / 2, guid[i - 1].sizeY() / 2, hvColRGB<unsigned char>(0)); labels[i].reset(labels[i - 1].sizeX() / 2, labels[i - 1].sizeY() / 2, 0); for (ii = 0; ii < guid[i].sizeX(); ii++) for (jj = 0; jj < guid[i].sizeY(); jj++) { hvColRGB<unsigned char> col[4]; col[0] = guid[i - 1].get(ii * 2, jj * 2); col[1] = guid[i - 1].get(ii * 2 + 1, jj * 2); col[2] = guid[i - 1].get(ii * 2, jj * 2 + 1); col[3] = guid[i - 1].get(ii * 2 + 1, jj * 2 + 1); unsigned char rr = (unsigned char)(((float)col[0].RED() + (float)col[1].RED() + (float)col[2].RED() + (float)col[3].RED()) / 4.0); unsigned char gg = (unsigned char)(((float)col[0].GREEN() + (float)col[1].GREEN() + (float)col[2].GREEN() + (float)col[3].GREEN()) / 4.0); guid[i].update(ii, jj, hvColRGB<unsigned char>(rr, gg, 0)); labels[i].update(ii, jj, labels[i - 1].get(ii * 2, jj * 2)); } //guid[i].shrink(&(guid[i - 1]), 0); gmask[i].shrink(gmask[i - 1]); #ifndef USE_NO_TEMPORARY_IMAGE_EXPORT sprintf(buff, "%s_spt_%02d_guidance.ppm", name, i); fd = fopen(buff, "wb"); if (fd == 0) { perror("cannot load file:"); } guid[i].savePPM(fd, 1); fclose(fd); hvPictRGB<unsigned char> labelsrgb(labels[i], 1); sprintf(buff, "%s_spt_%02d_guidancelabels.ppm", name, i); fd = fopen(buff, "wb"); if (fd == 0) { perror("cannot load file:"); } labelsrgb.savePPM(fd, 1); fclose(fd); #endif } // Set index uv map size at first level of the pyramid index.reset(guidance.sizeX() / factor, guidance.sizeY() / factor, hvVec2<int>()); // - associated synthesized maps of color, distance and labels (automatically derived from index uv map) synth[s].reset(guidance.sizeX() / factor , guidance.sizeY() / factor , hvColRGB<T>()); synthdist[s].reset(guidance.sizeX() / factor , guidance.sizeY() / factor , hvColRGB<T>()); synthlabels[s].reset(guidance.sizeX() / factor , guidance.sizeY() / factor , 0); // - timer auto endTime = std::chrono::high_resolution_clock::now(); float elapsedTime = static_cast<float>(std::chrono::duration_cast<std::chrono::milliseconds>(endTime - startTime).count()); std::cout << "- time: " << elapsedTime << " ms\n"; //------------------------------------------------ // [stage #2] SMART initialization //------------------------------------------------ // Smart initialization is used to better initialize the optimization algorithm sued during synthesis. // Originally, PCTS used a uniform tiling of UV coordinates and used jittering to cerate randomness. // Here, we do a kind of lazy "pre-synthesis" using the guidance map to search for good neighborhood. // UV coordinates will have a better 2D coordinates close to the guidance map (ex: thresholded PPTBF) startTime = std::chrono::high_resolution_clock::now(); std::cout << "\n---------------------------------------------------------------------------------------" << std::endl; std::cout << "\n[SMART INITIALIZATION stage]" << std::endl; printf("\n- smart blocs init...\n"); printf("- blocs init: %d,%d blocs (at lev %d, bsize=%d)...\n", index.sizeX() / (bsize), index.sizeY() / (bsize), s, bsize); if ( guidance.sizeX() % (factor*bsize) != 0 || guidance.sizeY() % (factor*bsize) != 0 ) { hvFatal( "guidance size must be divisible by (factor*bsize)" ); } // Block initialization this->smartInitialization( posx/factor-bsize, posy/factor-bsize, ERR, indweight, bsize, guid[s], labels[s], gmask[s], pyr[s], pyrdist[s], pyrlabels[s], index, synth[s], synthdist[s], synthlabels[s] ); // - timer endTime = std::chrono::high_resolution_clock::now(); elapsedTime = static_cast<float>(std::chrono::duration_cast<std::chrono::milliseconds>(endTime - startTime).count()); std::cout << "- time: " << elapsedTime << " ms\n"; // Temporary images to look at intermediate steps (for debug) // - il will display the current state of the uv map after smart initialization in terms of color, distance and labels. hvPictRGB<unsigned char> pinit(index.sizeX()*factor, index.sizeY()*factor, hvColRGB<unsigned char>(0)); hvPictRGB<unsigned char> finit(index.sizeX()*factor, index.sizeY()*factor, hvColRGB<unsigned char>(0)); hvPictRGB<unsigned char> labinit(index.sizeX()*factor, index.sizeY()*factor, hvColRGB<unsigned char>(0)); for (i = 0; i < index.sizeX(); i++) for (j = 0; j < index.sizeY(); j++) { hvVec2<int> pos = index.get(i, j); for (int ii = 0; ii < factor; ii++) for (int jj = 0; jj < factor; jj++) { pinit.update(i*factor + ii, j*factor + jj, example.get(pos.X()*factor + ii, pos.Y()*factor + jj)); finit.update(i*factor + ii, j*factor + jj, dist.get(pos.X()*factor + ii, pos.Y()*factor + jj)); labinit.update(i*factor + ii, j*factor + jj, hvColRGB<unsigned char>(exlabels.get(pos.X()*factor + ii, pos.Y()*factor + jj))); } } #ifndef USE_NO_TEMPORARY_IMAGE_EXPORT sprintf(buff, "%s_spt_%02d_blocinit.ppm", name, s); fd = fopen(buff, "wb"); if (fd == 0) { perror("cannot load file:"); } pinit.savePPM(fd, 1); fclose(fd); sprintf(buff, "%s_spt_%02d_distinit.ppm", name, s); fd = fopen(buff, "wb"); if (fd == 0) { perror("cannot load file:"); } finit.savePPM(fd, 1); fclose(fd); sprintf(buff, "%s_spt_%02d_labinit.ppm", name, s); fd = fopen(buff, "wb"); if (fd == 0) { perror("cannot load file:"); } labinit.savePPM(fd, 1); fclose(fd); #endif //printf("%s_spt_%02d_init\n", name, s); #ifndef USE_NO_TEMPORARY_IMAGE_EXPORT sprintf(buff, "%s_spt_%02d_init.ppm", name, s); fd = fopen(buff, "wb"); if (fd == 0) { perror("cannot load file:"); } synth[s].savePPM(fd, 1); fclose(fd); sprintf(buff, "%s_spt_%02d_dist.ppm", name, s); fd = fopen(buff, "wb"); if (fd == 0) { perror("cannot load file:"); } synthdist[s].savePPM(fd, 1); fclose(fd); hvPictRGB<unsigned char> synthlabrgb(synthlabels[s], 1); sprintf(buff, "%s_spt_%02d_distlabel.ppm", name, s); fd = fopen(buff, "wb"); if (fd == 0) { perror("cannot load file:"); } synthlabrgb.savePPM(fd, 1); fclose(fd); #endif //------------------------------------------------- // [stage #3] main SYNTHESIS stage //------------------------------------------------- startTime = std::chrono::high_resolution_clock::now(); std::cout << "\n---------------------------------------------------------------------------------------" << std::endl; std::cout << "\n[SYNTHESIS stage]\n" << std::endl; // Number of correction stages (originally 2 in PCTS) const int niter = nbCorrectionPasses; //synthdist[s].imagefromindex(pyrdist[s], index); printf("starting spt at level:%d, shift:%d,%d\n", s, posx / factor - bsize/factor, posy / factor - bsize/factor); // Launch the main synthesis algortihm this->semiProceduralTextureSynthesis_mainPipeline( name, STOPATLEVEL, posx / factor - bsize/factor, posy / factor - bsize/factor, pyr, pyrdist, pyrlabels, // exemplar maps synth, synthdist, synthlabels, // synthesized maps guid, labels, gmask, // guidance maps index, // index map (synthesized) weight, powr, s, factor, neighbor, niter, indweight ); // - timer endTime = std::chrono::high_resolution_clock::now(); elapsedTime = static_cast<float>(std::chrono::duration_cast<std::chrono::milliseconds>(endTime - startTime).count()); std::cout << "\nTOTAL time: " << elapsedTime << " ms\n"; } /****************************************************************************** * semiProceduralTextureSynthesis_mainPipeline * * Main algorithm alternating correction and upscaling passes. ******************************************************************************/ void semiProceduralTextureSynthesis_mainPipeline( const char *name, int STOPATLEVEL, int shiftx, int shifty, hvPictRGB<T> pyr[], hvPictRGB<T> pyrdist[], hvPict<unsigned char> pyrlabels[], hvPictRGB<T> synth[], hvPictRGB<T> synthdist[], hvPict<unsigned char> synthlabels[], hvPictRGB<T> guid[], hvPict<unsigned char> labels[], hvBitmap gmask[], hvArray2<hvVec2<int> > &index, double weight, double powr, int s, int factor, int neighbor, int niter, // nb correction passes float indweight ) // label error penalty { char buff[256]; int i, j, k; FILE *fd; // Gudance strength vary per pyramid level #ifndef USE_NO_GUIDANCE_RELAXATION double step = 1.0 / (double)( s + 1 ); #else double step = 1.0 / (double)( s + 2 ); // to avoid strength = 0 when s = 0 (at finest resolution) #endif double strength = 1.0 - step; hvArray2<hvVec2<int> > oldindex; hvPictRGB<unsigned char> prefine; hvBitmap refinebin; hvPictRGB<unsigned char> offsets(index.sizeX(), index.sizeY(), hvColRGB<unsigned char>()); for (i = 0; i < index.sizeX(); i++) for (j = 0; j < index.sizeY(); j++) { offsets.update(i, j, hvColRGB<unsigned char>((unsigned char)((double)index.get(i, j).X() / (double)pyr[s].sizeX() * 128.0 + 128.0), (unsigned char)((double)index.get(i, j).Y() / (double)pyr[s].sizeY() * 128.0 + 128.0), 0)); } #ifndef USE_NO_TEMPORARY_IMAGE_EXPORT sprintf(buff, "%s_spt_%02d_offsets.ppm", name, s); fd = fopen(buff, "wb"); if (fd == 0) { perror("cannot load file:"); } offsets.savePPM(fd, 1); fclose(fd); #endif // Iterate through pyramid levels //indweight = 0.0; while ( s > 0 ) { printf( "\n-----------------------------------" ); printf( "\nlevel %d, factor %d\n", s, factor ); printf( "-----------------------------------\n" ); auto startTime = std::chrono::high_resolution_clock::now(); // Iterate through correction passes (usually 2) for ( k = 0; k < niter; k++ ) { oldindex.clone(index); prefine.reset(index.sizeX(), index.sizeY(), hvColRGB<unsigned char>(0)); if ( s >= STOPATLEVEL ) { #ifndef USE_NO_GUIDANCE_RELAXATION // Correction pass synth[ s ].execute_correctionPass( s, shiftx+k, shifty+k, k % 2 != 0, k % 2 == 0 ? indweight : 0.0, 6, synthdist[s], synthlabels[s], pyr[s], pyrdist[s], pyrlabels[s], guid[s], labels[s], gmask[s], weight, neighbor, k % 2 == 0 ? pow(strength, powr) : 0.0, index, refinebin ); #else // Correction pass synth[ s ].execute_correctionPass( s, // pyramid level shiftx+k, shifty+k, /*k % 2 != 0*/false, // remove doubles (only at 2nd correction step) indweight, // label weight (none at at 2nd correction step) 6, // nb samples to search randomly around current candidate synthdist[s], synthlabels[s], // synthesized distance and labels pyr[s], pyrdist[s], pyrlabels[s], // exemplar color, distance and labels guid[s], labels[s], gmask[s], // guidance pptbf, labels and mask weight, // weight between color and distance neighbor, // neighbor size for MSE (during best candidate search) pow( strength, powr ), // guidance weight index, // index map (uv) refinebin ); #endif } else { refinebin.reset( synth[s].sizeX(), synth[s].sizeY(), false ); } hvPictRGB<unsigned char> offsets(index.sizeX(), index.sizeY(), hvColRGB<unsigned char>()); for (i = 0; i < index.sizeX(); i++) for (j = 0; j < index.sizeY(); j++) { hvVec2<int> npos = index.get(i, j); offsets.update(i, j, hvColRGB<unsigned char>((unsigned char)((double)npos.X() / (double)pyr[s].sizeX() * 128.0 + 128.0), (unsigned char)((double)npos.Y() / (double)pyr[s].sizeY() * 128.0 + 128.0), 0)); //if (npos.X() != oldindex.get(i, j).X() || npos.Y() != oldindex.get(i, j).Y()) if (refinebin.get(i, j)) prefine.update(i, j, synth[s].get(i, j)); else prefine.update(i, j, hvColRGB<unsigned char>(255)); } #ifndef USE_NO_TEMPORARY_IMAGE_EXPORT sprintf(buff, "%s_spt_%02d_corr%doffsets.ppm", name, s, k); fd = fopen(buff, "wb"); if (fd == 0) { perror("cannot load file:"); } offsets.savePPM(fd, 1); fclose(fd); sprintf(buff, "%s_spt_%02d_corr%d.ppm", name, s, k); fd = fopen(buff, "wb"); if (fd == 0) { perror("cannot load file:"); } synth[s].savePPM(fd, 1); fclose(fd); sprintf(buff, "%s_spt_%02d_dist%d.ppm", name, s, k); fd = fopen(buff, "wb"); if (fd == 0) { perror("cannot load file:"); } synthdist[s].savePPM(fd, 1); fclose(fd); sprintf(buff, "%s_spt_%02d_ref%d.ppm", name, s, k); fd = fopen(buff, "wb"); if (fd == 0) { perror("cannot load file:"); } prefine.savePPM(fd, 1); fclose(fd); #endif //printf("hit return\n"); fgets(buff, 5, stdin); } // Update synthesized color, distance and labels synth[s - 1].upscaleJitterPass(pyr[s - 1], 2, 0, index); synthdist[s - 1].imagefromindex(pyrdist[s - 1], index); synthlabels[s - 1].imagefromindex(pyrlabels[s - 1], index); // Update current LOD of the pyramid s--; factor /= 2; strength -= step; if (strength < 0.0) strength = 0.0; shiftx *= 2; shifty *= 2; #ifndef USE_NO_TEMPORARY_IMAGE_EXPORT sprintf(buff, "%s_spt_%02d_init.ppm", name, s); fd = fopen(buff, "wb"); if (fd == 0) { perror("cannot load file:"); } synth[s].savePPM(fd, 1); fclose(fd); sprintf(buff, "%s_spt_%02d_dist.ppm", name, s); fd = fopen(buff, "wb"); if (fd == 0) { perror("cannot load file:"); } synthdist[s].savePPM(fd, 1); fclose(fd); offsets.reset(index.sizeX(), index.sizeY(), hvColRGB<unsigned char>()); for (i = 0; i < index.sizeX(); i++) for (j = 0; j < index.sizeY(); j++) { offsets.update(i, j, hvColRGB<unsigned char>((unsigned char)((double)index.get(i, j).X() / (double)pyr[s].sizeX() * 128.0 + 128.0), (unsigned char)((double)index.get(i, j).Y() / (double)pyr[s].sizeY() * 128.0 + 128.0), 0)); } sprintf(buff, "%s_spt_%02d_offsets.ppm", name, s); fd = fopen(buff, "wb"); if (fd == 0) { perror("cannot load file:"); } offsets.savePPM(fd, 1); fclose(fd); #endif // - timer auto endTime = std::chrono::high_resolution_clock::now(); float elapsedTime = static_cast<float>(std::chrono::duration_cast<std::chrono::milliseconds>(endTime - startTime).count()); std::cout << "\ntime: " << elapsedTime << " ms\n"; } // Final correction pass oldindex.clone(index); prefine.reset(index.sizeX(), index.sizeY(), hvColRGB<unsigned char>(0)); if (s == 0) { printf("\n-----------------------------------"); printf("\nfinal correction pass..."); printf("\n-----------------------------------\n"); auto startTime = std::chrono::high_resolution_clock::now(); #ifndef USE_NO_GUIDANCE_RELAXATION if (STOPATLEVEL == 0) synth[s].execute_correctionPass(s, shiftx, shifty, false, 0.0, 4, synthdist[s], synthlabels[s], pyr[s], pyrdist[s], pyrlabels[s], guid[s], labels[s], gmask[s], weight, neighbor, 0.0, index, refinebin); #else if ( STOPATLEVEL == 0 ) { synth[s].execute_correctionPass( s, // pyramid level shiftx, shifty, false, // remove doubles indweight, // label error penalty 4, // nb samples to search randomly around current candidate synthdist[s], synthlabels[s], // synthesized maps pyr[s], pyrdist[s], pyrlabels[s], // exemplar maps guid[s], labels[s], gmask[s], // guidance maps weight, // weight between color and distance neighbor, // neighbor size for MSE (during best candidate search) pow( strength, powr ), // guidance weight index, // index map (synthesized uv) refinebin ); } #endif this->clone(synth[s], 0, 0, synth[s].sizeX() - 1, synth[s].sizeY() - 1); // - timer auto endTime = std::chrono::high_resolution_clock::now(); float elapsedTime = static_cast<float>(std::chrono::duration_cast<std::chrono::milliseconds>(endTime - startTime).count()); std::cout << "\ntime: " << elapsedTime << " ms\n"; // Update temporary images offsets.reset(index.sizeX(), index.sizeY(), hvColRGB<unsigned char>()); for (i = 0; i < index.sizeX(); i++) for (j = 0; j < index.sizeY(); j++) { //offsets.update(i, j, hvColRGB<unsigned char>((unsigned char)((double)index.get(i, j).X() / (double)pyr[s].sizeX() * 128.0 + 128.0), // (unsigned char)((double)index.get(i, j).Y() / (double)pyr[s].sizeY() * 128.0 + 128.0), 0)); hvVec2<int> npos = index.get(i, j); offsets.update(i, j, hvColRGB<unsigned char>((unsigned char)((double)npos.X() / (double)pyr[s].sizeX() * 128.0 + 128.0), (unsigned char)((double)npos.Y() / (double)pyr[s].sizeY() * 128.0 + 128.0), 0)); if (npos.X() != oldindex.get(i, j).X() || npos.Y() != oldindex.get(i, j).Y()) prefine.update(i, j, hvColRGB<unsigned char>(255)); else prefine.update(i, j, hvColRGB<unsigned char>(0)); } } #ifndef USE_NO_TEMPORARY_IMAGE_EXPORT sprintf(buff, "%s_semiproc_offsets.ppm", name); fd = fopen(buff, "wb"); if (fd == 0) { perror("cannot load file:"); } offsets.savePPM(fd, 1); fclose(fd); sprintf(buff, "%s_semiproc_dist.ppm", name); fd = fopen(buff, "wb"); if (fd == 0) { perror("cannot load file:"); } synthdist[s].savePPM(fd, 1); fclose(fd); hvPictRGB<unsigned char> labrgb(synthlabels[s], 1); sprintf(buff, "%s_semiproc_labels.ppm", name); fd = fopen(buff, "wb"); if (fd == 0) { perror("cannot load file:"); } labrgb.savePPM(fd, 1); fclose(fd); sprintf(buff, "%s_semiproc_refine.ppm", name); fd = fopen(buff, "wb"); if (fd == 0) { perror("cannot load file:"); } prefine.savePPM(fd, 1); fclose(fd); #endif } /****************************************************************************** * upscaleJitterPass() * * After correction, upscale texture by coping pixel to next finest LOD in pyramid ******************************************************************************/ void upscaleJitterPass( const hvPictRGB<T> &example, int scale, int jitter, hvArray2<hvVec2<int> > &index ) { this->reset(index.sizeX()*scale, index.sizeY()*scale, hvColRGB<T>()); hvArray2<hvVec2<int> > newid(index.sizeX()*scale, index.sizeY()*scale, hvVec2<int>()); int i, j, ii, jj; for (i = 0; i < index.sizeX(); i++) for (j = 0; j < index.sizeY(); j++) { for (ii = 0; ii < scale; ii++) for (jj = 0; jj < scale; jj++) { hvVec2<int> pos = index.get(i, j); // Upscale position int px = pos.X()*scale + ii, py = pos.Y()*scale + jj; px += (int)(((double)rand() / (double)RAND_MAX*2.0 - 1.0)*(double)(jitter)); if (px < 0) px = 0; if (px >= example.sizeX()) px = example.sizeX() - 1; py += (int)(((double)rand() / (double)RAND_MAX*2.0 - 1.0)*(double)(jitter)); if (py < 0) py = 0; if (py >= example.sizeY()) py = example.sizeY() - 1; if (i*scale + ii < this->sizeX() && j*scale + jj < this->sizeY()) { this->update(i*scale + ii, j*scale + jj, example.get(px, py)); newid.update(i*scale + ii, j*scale + jj, hvVec2<int>(px, py)); } } } // Swap data to original image buffer index.reset(newid.sizeX(), newid.sizeY(), hvVec2<int>()); for (i = 0; i < index.sizeX(); i++) for (j = 0; j < index.sizeY(); j++) { index.update(i, j, newid.get(i, j)); } } /****************************************************************************** * execute_correctionPass() * * Correction pass to look for better candidate pixels * - look for better UV coordinates by measuring distance/similarity for a neighborhood (ex: 3x3 pixels) ******************************************************************************/ void execute_correctionPass( int sscale, // pyramid level int shiftx, int shifty, bool wdoublon, // remove doubles (only at 2nd correction step) float indweight, // label weight (none at at 2nd correction step) int samples, // nb samples to search randomly around current candidate hvPictRGB< T >& synthdist, hvPict< unsigned char >& synthlabels, // synthesized distance and label maps const hvPictRGB< T >& example, const hvPictRGB< T >& distance, const hvPict< unsigned char >& exlabels, // exemplar color, distance and label maps const hvPictRGB< T >& guidance, const hvPict< unsigned char >& labels, const hvBitmap& mask, // guidance pptbf, labels and mask maps double weight, // weight between color and distance int neighbor, // neighbor size for MSE (during best candidate search) double strength, // guidance weight (distances and labels) hvArray2< hvVec2< int > >& index, // index map (synthesized uv) hvBitmap& refine ) { #ifdef USE_MULTITHREADED_SYNTHESIS MyThreadPool threadPool; #endif // Min threshold error for guidance distance (i.e. PPTBF) to check whether or not to refine (per pixel) // - linear interpolation between [0.05;2.0] based on "strength" in [0.0;1.0] // - i.e: [min,max]=[0.05;2.0] is the threshold error on guidance distance const float MINTHRESH = 0.05 * strength + 0.2 * ( 1.0 - strength ); printf( "\n[x] strength=%g, minthresh to change=%g, scale=%d, index=%d,%d\n", strength, MINTHRESH, sscale, shiftx, shifty ); int nneigh = 2; int nextx[] = { 0,1,0,1 }; int nexty[] = { 0,1,1,0 }; int count = 0; refine.reset(this->sizeX(), this->sizeY(), false); //--------------------------------------------------------------------- // Pre-processing pass : check whether or not to refine (per pixel) //--------------------------------------------------------------------- std::cout << "\npre-processing: check whether or not to refine" << std::endl; // - timer auto startTime = std::chrono::high_resolution_clock::now(); // Iterate through the image and, for each pixel, check whether or not to refine // based on different criteria : // - not too far away for current spatial position // - in a region of guidance (mask)- // - and with an error lower than a given threshold for guidance maps (pptbf and labels) for ( int jj = 0; jj < this->sizeY(); jj++ ) for ( int ii = 0; ii < this->sizeX(); ii++ ) { // Retrieve neighbor pixels in index map int ix[16], iy[16], px[16], py[16]; ix[0] = index.get((ii - 1) >= 0 ? ii - 1 : 0, (jj - 1) >= 0 ? jj - 1 : 0).X(); iy[0] = index.get((ii - 1) >= 0 ? ii - 1 : 0, (jj - 1) >= 0 ? jj - 1 : 0).Y(); ix[1] = index.get((ii + 2) >= index.sizeX() ? index.sizeX() - 1 : ii + 2, (jj - 1) >= 0 ? jj - 1 : 0).X(); iy[1] = index.get((ii + 2) >= index.sizeX() ? index.sizeX() - 1 : ii + 2, (jj - 1) >= 0 ? jj - 1 : 0).Y(); ix[2] = index.get((ii - 1) >= 0 ? ii - 1 : 0, (jj + 2) >= index.sizeY() ? index.sizeY() - 1 : jj + 2).X(); iy[2] = index.get((ii - 1) >= 0 ? ii - 1 : 0, (jj + 2) >= index.sizeY() ? index.sizeY() - 1 : jj + 2).Y(); ix[3] = index.get((ii + 2) >= index.sizeX() ? index.sizeX() - 1 : ii + 2, (jj + 2) >= index.sizeY() ? index.sizeY() - 1 : jj + 2).X(); iy[3] = index.get((ii + 2) >= index.sizeX() ? index.sizeX() - 1 : ii + 2, (jj + 2) >= index.sizeY() ? index.sizeY() - 1 : jj + 2).Y(); px[0] = ii - 1 >= 0 ? ii - 1 : 0; py[0] = jj - 1 >= 0 ? jj - 1 : 0; px[1] = (ii + 2) >= this->sizeX() ? this->sizeX() - 1 : ii + 2; py[1] = jj - 1 >= 0 ? jj - 1 : 0; px[2] = ii - 1 >= 0 ? ii - 1 : 0; py[2] = (jj + 2) >= this->sizeY() ? this->sizeY() - 1 : jj + 2; px[3] = (ii + 2) >= this->sizeX() ? this->sizeX() - 1 : ii + 2; py[3] = (jj + 2) >= this->sizeY() ? this->sizeY() - 1 : jj + 2; // Compute associated average spatial position in exemplar int avgx = (ix[0] + ix[1] + ix[2] + ix[3]) / 4; int avgy = (iy[0] + iy[1] + iy[2] + iy[3]) / 4; int maxx = 0, maxy = 0; for (int k = 0; k < 4; k++) { int deltax = ix[k] - avgx; if (deltax < 0) deltax = -deltax; int deltay = iy[k] - avgy; if (deltay < 0) deltay = -deltay; if (deltax > maxx) maxx = deltax; if (deltay > maxy) maxy = deltay; } // Check if not too far away from current spatial position bool prefine = true; if ( maxx <= 2 * neighbor && maxy <= 2 * neighbor ) { // Check whether or not we are in the mask region if ( !mask.get( ii, jj ) ) { prefine = false; } else { // If yes, compute error on guidance (pptbf + labels) bool var = false; int iix = index.get( ii, jj ).X(); int iiy = index.get( ii, jj ).Y(); // Check for guidance distance error (pptbf) (MSE L2) float errg = (float)abs( distance.get(iix, iiy).GREEN() - guidance.get(ii, jj).GREEN() ) / 255.0; float errr = (float)abs( distance.get(iix, iiy).RED() - guidance.get(ii, jj).RED() ) / 255.0; float errb = (float)abs( distance.get(iix, iiy).BLUE() - guidance.get(ii, jj).BLUE() ) / 255.0; if ( errg*errg + errr*errr + errb*errb > 3.0 * ( MINTHRESH * MINTHRESH ) ) { var = true; } // Check for guidance label error if ( indweight > 0.0 && exlabels.get( iix, iiy ) != labels.get( ii, jj ) ) { var = true; } if (!var) prefine = false; } if (!prefine) count++; } // Update refinement map refine.set( ii, jj, prefine ); } // - timer auto endTime = std::chrono::high_resolution_clock::now(); float elapsedTime = static_cast< float >( std::chrono::duration_cast< std::chrono::milliseconds >( endTime - startTime ).count() ); std::cout << "time: " << elapsedTime << " ms\n"; //--------------------------------------------------------------------- // Refinement pass //--------------------------------------------------------------------- std::cout << "\nrefinement pass..." << std::endl; // - timer startTime = std::chrono::high_resolution_clock::now(); float nstrength = strength; for ( int k = 0; k < 1; k++ ) // number of refinement pass { // Correction subpasses : "jump" pixels because the pixels are corrected according to neighborhoods that are also changing // - we partition pass into a sequence of subpasses on subsets of nonadjacent pixels //for ( i = 0; i < nneigh; i++ ) for ( j = 0; j < nneigh; j++ ) //for (i=0; i<nneigh*nneigh; i++) const int subpassCorrectionStep = 3; // because of the 5x5 neighborhood collision/overlapping during correction for ( int i = 0; i < subpassCorrectionStep; i++ ) for ( int j = 0; j < subpassCorrectionStep; j++ ) { #ifdef USE_MULTITHREADED_SYNTHESIS std::mutex mutex; int nextPixelToProcessX = i; int nextPixelToProcessY = j; bool isRunning = true; threadPool.AppendTask( [&](const MyThreadPool::ThreadData* thread ) { while ( isRunning ) { mutex.lock(); int iii = nextPixelToProcessX; int jjj = nextPixelToProcessY; nextPixelToProcessX += subpassCorrectionStep; if ( nextPixelToProcessX >= this->sizeX() ) { nextPixelToProcessX = i; nextPixelToProcessY += subpassCorrectionStep; isRunning = ( nextPixelToProcessY < this->sizeY() ); } mutex.unlock(); // Manage exeception / handle error if ( iii >= this->sizeX() || jjj >= this->sizeY() ) { //printf( "\nOK, error handled ! :)" ); continue; } // Retrieve current neighborhood in index map (5x5) int px, py; int ix[25], iy[25]; for ( int ri = 0; ri < 5; ri++ ) for ( int rj = 0; rj < 5; rj++ ) { //ix[0] = index.get(iii, jjj).X(); iy[0] = index.get(iii, jjj).Y(); //ix[1] = index.get((iii + 2) % index.sizeX(), jjj).X(); iy[1] = index.get((iii + 2) % index.sizeX(), jjj).Y(); //ix[2] = index.get(iii, (jjj + 2) % index.sizeY()).X(); iy[2] = index.get(iii, (jjj + 2) % index.sizeY()).Y(); //ix[3] = index.get((iii + 2) % index.sizeX(), (jjj + 2) % index.sizeY()).X(); iy[3] = index.get((iii + 2) % index.sizeX(), (jjj + 2) % index.sizeY()).Y(); int pi = iii + ri - 2; if (pi < 0) pi = 0; int pj = jjj + rj - 2; if (pj < 0) pj = 0; ix[ ri + rj * 5 ] = index.get( pi >= index.sizeX() ? index.sizeX() - 1 : pi, pj >= index.sizeY() ? index.sizeY() - 1 : pj ).X(); iy[ ri + rj * 5 ] = index.get( pi >= index.sizeX() ? index.sizeX() - 1 : pi, pj >= index.sizeY() ? index.sizeY() - 1 : pj ).Y(); } // Check if refinement is required if ( refine.get( iii, jjj ) ) { // Refine candidate (look for a better one and store its exemplar's position in (px,py) this->refineBestNeighborMatchwdistguidanceV2( shiftx, shifty, indweight, samples, synthdist, synthlabels, example, distance, exlabels, guidance, labels, mask, weight, mask.get( iii, jjj ) ? nstrength : 0.0, iii, jjj, neighbor, ix, iy, 25, px, py, // returned best candidate position in exemplar ix, iy, 0 ); // Update index map index.update( iii, jjj, hvVec2< int >( px, py ) ); // Update synthesis (color, distance, labels...) this->update( iii, jjj, example.get( px, py ) ); synthdist.update( iii, jjj, distance.get( px, py ) ); synthlabels.update( iii, jjj, exlabels.get( px, py ) ); } } }); #else // subpasses depending on size of neighborhood //for (ii = nextx[i]; ii < this->sizeX(); ii += nneigh) for (jj = nexty[i]; jj < this->sizeY(); jj += nneigh) //for ( ii = i; ii < this->sizeX(); ii += nneigh ) for ( jj = j; jj < this->sizeY(); jj += nneigh ) for (int jj = j; jj < this->sizeY(); jj += subpassCorrectionStep) for ( int ii = i; ii < this->sizeX(); ii += subpassCorrectionStep ) { int px, py; int ix[25], iy[25]; for ( int ri = 0; ri < 5; ri++ ) for ( int rj = 0; rj < 5; rj++ ) { //ix[0] = index.get(ii, jj).X(); iy[0] = index.get(ii, jj).Y(); //ix[1] = index.get((ii + 2) % index.sizeX(), jj).X(); iy[1] = index.get((ii + 2) % index.sizeX(), jj).Y(); //ix[2] = index.get(ii, (jj + 2) % index.sizeY()).X(); iy[2] = index.get(ii, (jj + 2) % index.sizeY()).Y(); //ix[3] = index.get((ii + 2) % index.sizeX(), (jj + 2) % index.sizeY()).X(); iy[3] = index.get((ii + 2) % index.sizeX(), (jj + 2) % index.sizeY()).Y(); int pi = ii + ri - 2; if (pi < 0) pi = 0; int pj = jj + rj - 2; if (pj < 0) pj = 0; ix[ri + rj * 5] = index.get( pi >= index.sizeX() ? index.sizeX() - 1 : pi, pj >= index.sizeY() ? index.sizeY() - 1 : pj ).X(); iy[ri + rj * 5] = index.get( pi >= index.sizeX() ? index.sizeX() - 1 : pi, pj >= index.sizeY() ? index.sizeY() - 1 : pj ).Y(); } //if (!refine) printf("No refine in %d,%d\n",ii, jj); //this->refineBestNeighborMatch(example, ii, jj, neighbor, ix, iy, 4, px, py); //this->refineBestNeighborMatchwdist(synthdist, example, distance, weight, ii, jj, neighbor, ix, iy, 4, px, py); if ( refine.get( ii, jj ) ) { this->refineBestNeighborMatchwdistguidanceV2( shiftx, shifty, indweight, samples, synthdist, synthlabels, example, distance, exlabels, guidance, labels, mask, weight, mask.get(ii, jj) ? nstrength : 0.0, ii, jj, neighbor, ix, iy, 25, px, py, ix, iy, 0 ); this->update(ii, jj, example.get(px, py)); synthdist.update(ii, jj, distance.get(px, py)); synthlabels.update(ii, jj, exlabels.get(px, py)); index.update(ii, jj, hvVec2<int>(px, py)); } //newthis.update(ii, jj, example.get(px, py)); //newdist.update(ii, jj, distance.get(px, py)); //newindex.update(ii, jj, hvVec2<int>(px, py)); } #endif } printf( "refined %d / %d pixels.\n", this->sizeX() * this->sizeX() - count, this->sizeX() * this->sizeX() ); //this->clone(newthis, 0, 0, this->sizeX() - 1, this->sizeY() - 1); //synthdist.clone(newdist, 0, 0, newdist.sizeX() - 1, newdist.sizeY() - 1); //index.clone(newindex); if ( strength < 0.5f ) { // after 2nd pass, no constrain to enforce local coherence nstrength = 0.0; } } // - timer endTime = std::chrono::high_resolution_clock::now(); elapsedTime = static_cast< float >( std::chrono::duration_cast< std::chrono::milliseconds >( endTime - startTime ).count() ); std::cout << "time: " << elapsedTime << " ms\n"; } /****************************************************************************** * ... ******************************************************************************/ hvColRGB<double> getDoG(int x, int y, int ss) { int i, j, nn=0; hvColRGB<double> cc(0.0); for (i = -ss; i <= ss; i++) for (j = -ss; j <= ss; j++) { if (x + i >= 0 && y + j >= 0 && x + i < this->sizeX() && y + j < this->sizeY()) { cc += (hvColRGB<double>)this->get(x + i, y + j); nn++; } } cc.scale(1.0 / (double)nn); return (hvColRGB<double>)this->get(x, y) - cc; } /****************************************************************************** * ... ******************************************************************************/ template <class U> void blend(const hvPictRGB<T> &example, const hvPict<U> &alpha, U scal, double power, const hvBitmap &mask) { int i,j; for (i=0; i<this->sizeX(); i++) for (j=0; j<this->sizeY(); j++) { if (mask.get(i,j)) { double coeff = pow((double)alpha.get(i,j)/(double)scal, power); hvColRGB<T> col = this->get(i,j); hvColRGB<T> colex = example.get(i,j); hvColRGB<T> colres; colres.blend(colex,col, coeff); this->update(i,j,colres); } } } /****************************************************************************** * ... ******************************************************************************/ template <class U> void blendRect(int px, int py, int x, int y, int sx, int sy, const hvPictRGB<T> &example, const hvPict<U> &alpha, U scal, double power, const hvBitmap &mask, bool mshift=true) { int i,j; for (i=0; i<sx; i++) for (j=0; j<sy; j++) { if (mask.get((mshift?x:0)+i,(mshift?y:0)+j)) { if (px+i>=0 && px+i<this->sizeX() && py+j>=0 && py+j<this->sizeY()) { double coeff = pow((double)alpha.get((mshift?x:0)+i,(mshift?y:0)+j)/(double)scal, power); hvColRGB<T> col = this->get(px+i,py+j); hvColRGB<T> colex = example.get(x+i,y+j); hvColRGB<T> colres; colres.blend(colex,col, coeff); //if (coeff<1.0) colres=hvColRGB<T>(T(255),T(255),T(0)); //colres = hvColRGB<T>(0); this->update(px+i,py+j,colres); } } } } /****************************************************************************** * ... ******************************************************************************/ template <class U> void shiftedblend(int dx, int dy, const hvPictRGB<T> &example, const hvPict<U> &alpha, U scal, double power, const hvBitmap &mask, hvBitmap &affected, hvPict<hvVec2<int> > *index = 0) { int i,j; for (i=0; i<this->sizeX(); i++) for (j=0; j<this->sizeY(); j++) { int x = i-dx; if (x<0) x += mask.sizeX(); else if (x>=mask.sizeX()) x -= mask.sizeX(); int y = j-dy; if (y<0) y += mask.sizeY(); else if (y>=mask.sizeY()) y -= mask.sizeY(); if (mask.get(x,y)) { double coeff = pow((double)alpha.get(x,y)/(double)scal, power); hvColRGB<T> col = this->get(i,j); hvColRGB<T> colex = example.get(x,y); hvColRGB<T> colres; colres.blend(colex,col, coeff); this->update(i,j,colres); affected.set(i,j,true); if (index != 0) index->update(i,j,hvVec2<int>(x, y)); } } } /****************************************************************************** * ... ******************************************************************************/ void seedfill(const hvColRGB<T> &col, int x, int y, hvBitmap &bm, hvVec2<int> &min, hvVec2<int> &max) const { if (x<0 || y<0 || x>= this->sizeX() || y>= this->sizeY()) return; if (!(this->get(x,y).equals(col))) return; if (bm.get(x,y)) return; bm.set(x,y,true); min.keepMin(min,hvVec2<int>(x,y)); max.keepMax(max,hvVec2<int>(x,y)); int i,a,b; for (i=x+1; i<this->sizeX() && (!bm.get(i,y)) && this->get(i,y).equals(col); i++) { bm.set(i,y, true); max.keepMax(max,hvVec2<int>(i,y)); } b=i-1; for (i=x-1; i>=0 && (!bm.get(i,y)) && this->get(i,y).equals(col); i--) { bm.set(i,y, true); min.keepMin(min,hvVec2<int>(i,y)); } a = i+1; for (i=a; i<=b; i++) { seedfill(col,i,y-1,bm,min,max); seedfill(col,i,y+1,bm,min,max); } } /****************************************************************************** * ... ******************************************************************************/ void seedfill(const hvColRGB<T> &col, int x, int y, hvBitmap &bm, hvVec2<int> &min, hvVec2<int> &max, std::vector<hvVec2<unsigned short> > &lpts) const { if (x<0 || y<0 || x>= this->sizeX() || y>= this->sizeY()) return; if (!(this->get(x,y).equals(col))) return; if (bm.get(x,y)) return; bm.set(x,y,true); lpts.push_back(hvVec2<unsigned short>((unsigned short)x,(unsigned short)y)); min.keepMin(min,hvVec2<int>(x,y)); max.keepMax(max,hvVec2<int>(x,y)); int i,a,b; for (i=x+1; i<this->sizeX() && (!bm.get(i,y)) && this->get(i,y).equals(col); i++) { bm.set(i,y, true); max.keepMax(max,hvVec2<int>(i,y)); } b=i-1; for (i=x-1; i>=0 && (!bm.get(i,y)) && this->get(i,y).equals(col); i--) { bm.set(i,y, true); min.keepMin(min,hvVec2<int>(i,y)); } a = i+1; for (i=a; i<=b; i++) { seedfill(col,i,y-1,bm,min,max); seedfill(col,i,y+1,bm,min,max); } } /****************************************************************************** * ... ******************************************************************************/ hvVec2<int> chooseMinSquareDiff(int bx, int by, int bsx, int bsy, int x,int y,int sx,int sy, const hvPictRGB<T> &inpict, hvColRGB<double> &minerr) { int i,j; hvColRGB<double> res; double minv=0.0; hvVec2<int> minpos(bx,by); bool first=true; for (i=bx; i<bx+bsx; i+=2) for (j=by; j<by+bsy; j+=2) { //printf("mask at %d,%d, %s\n", cx-i+x,cy-j+y, mask.get(cx-i+x,cy-j+y)?"true":"flase"); this->squareDifference(255.0,i,j,x,y,sx,sy,inpict,res,4); double vv = res.norm(); if (first) { first=false; minv=vv; minpos=hvVec2<int>(i,j); minerr=res; } else if (vv<minv) { minv=vv; minpos=hvVec2<int>(i,j); minerr=res; } } return minpos; } /****************************************************************************** * ... ******************************************************************************/ hvVec2<int> chooseMinSquareDiffBorder(int bx, int by, int bsx, int bsy, int x, int y, int sx, int sy, const hvPictRGB<T> &inpict, hvColRGB<double> &minerr) { int i, j; hvColRGB<double> res; double minv = 0.0; hvVec2<int> minpos(bx, by); bool first = true; for (i = bx; i<bx + bsx; i += 2) for (j = by; j<by + bsy; j += 2) { //printf("mask at %d,%d, %s\n", cx-i+x,cy-j+y, mask.get(cx-i+x,cy-j+y)?"true":"flase"); this->squareDifferenceBorder(255.0, i, j, x, y, sx, sy, inpict, res, 4); double vv = res.norm(); if (first) { first = false; minv = vv; minpos = hvVec2<int>(i, j); minerr = res; } else if (vv<minv) { minv = vv; minpos = hvVec2<int>(i, j); minerr = res; } } return minpos; } /****************************************************************************** * ... ******************************************************************************/ hvVec2<int> chooseMinSquareDiff(int bx, int by, int bsx, int bsy, int x,int y,int sx,int sy, const hvPictRGB<T> &inpict, const hvBitmap &mask, int cx, int cy, hvColRGB<double> &minerr) { int i,j; hvColRGB<double> res; bool first=true; double minv=0.0; hvVec2<int> minpos(bx,by); for (i=bx; i<bx+bsx; i+=2) for (j=by; j<by+bsy; j+=2) { //if (mask.get(cx-i+x,cy-j+y) && mask.get(cx-i+x-1,cy-j+y) && mask.get(cx-i+x+1,cy-j+y) && mask.get(cx-i+x,cy-j+y-1) && mask.get(cx-i+x,cy-j+y+1)) if (mask.get(cx-i+x,cy-j+y)) { //printf("mask at %d,%d, %s\n", cx-i+x,cy-j+y, mask.get(cx-i+x,cy-j+y)?"true":"flase"); this->squareDifference(255.0,i,j,x,y,sx,sy,inpict,mask,res); double vv = res.norm(); if (first) { first=false; minv=vv; minpos=hvVec2<int>(i,j); minerr=res; } else if (vv<minv) { minv=vv; minpos=hvVec2<int>(i,j); minerr=res; } } } if (first) { printf("warning cannot find best minsquare diff on %d,%d\n", cx,cy); } return minpos; } /****************************************************************************** * ... ******************************************************************************/ hvVec2<int> chooseWeightedMinSquareDiff(int bx, int by, int bsx, int bsy, int x,int y,int sx,int sy, const hvPictRGB<T> &inpict, const hvBitmap &mask, const hvPict<double> &weight, int cx, int cy, hvColRGB<double> &minerr) { int i,j; hvColRGB<double> res; bool first=true; double minv=0.0; hvVec2<int> minpos(bx,by); for (i=bx; i<bx+bsx; i+=2) for (j=by; j<by+bsy; j+=2) { //if (mask.get(cx-i+x,cy-j+y) && mask.get(cx-i+x-1,cy-j+y) && mask.get(cx-i+x+1,cy-j+y) && mask.get(cx-i+x,cy-j+y-1) && mask.get(cx-i+x,cy-j+y+1)) if (mask.get(cx-i+x,cy-j+y)) { //printf("mask at %d,%d, %s\n", cx-i+x,cy-j+y, mask.get(cx-i+x,cy-j+y)?"true":"flase"); this->weightedSquareDifference(255.0,i,j,x,y,sx,sy,inpict,weight,res); double vv = res.norm(); if (first) { first=false; minv=vv; minpos=hvVec2<int>(i,j); minerr=res; } else if (vv<minv) { minv=vv; minpos=hvVec2<int>(i,j); minerr=res; } } } if (first) { printf("warning cannot find best minsquare diff on %d,%d\n", cx,cy); } return minpos; } }; //////////////////////////////////////////////////////////// template <class T> class hvPictRGBA : public hvField2< hvColRGBA<T> > //////////////////////////////////////////////////////////// { public: hvPictRGBA<T>() : hvField2< hvColRGBA<T> >() { } hvPictRGBA<T>(int sx, int sy, const hvColRGBA<T> &nil) : hvField2< hvColRGBA<T> >(sx, sy, nil),hvArray2< hvColRGBA<T> >(sx, sy, nil) { } void clone(const hvPictRGBA<T> &pict,int x, int y, int sx, int sy) { hvField2< hvColRGBA<T> >::reset(sx-x+1, sy-y+1, hvColRGBA<T>(0)); int i,j; for (i=x; i<=sx; i++) for (j=y; j<=sy; j++) { this->update(i-x,j-y,pict.get(i,j)); } } void clone(const hvPictRGB<T> &pict,const hvPict<T> &pa, int x, int y, int sx, int sy) { hvField2< hvColRGBA<T> >::reset(sx-x+1, sy-y+1, hvColRGBA<T>(0)); int i,j; for (i=x; i<=sx; i++) for (j=y; j<=sy; j++) { hvColRGB<T> col = pict.get(i,j); hvColRGBA<T> cc(col, pa.get(i,j)); //printf("clone %d,%d -> %d,%d,%d,%d\n", i,j,(int)cc.RED(), (int)cc.GREEN(), (int)cc.BLUE(), (int)cc.ALPHA()); this->update(i-x,j-y,cc); } } void copy(int x, int y, const hvPictRGBA<T> &pict) { int i,j; for (i=0; i<pict.sizeX(); i++) for (j=0; j<pict.sizeY(); j++) { this->update(x+i,y+j,pict.get(i,j)); } } void copyRect(int px, int py, int x, int y, int sx, int sy, const hvPictRGBA<T> &pict, const hvBitmap &mask) { int i,j; for (i=0; i<sx; i++) for (j=0; j<sy; j++) { if (mask.get(x+i, y+j)) { this->update(px+i,py+j,pict.get(x+i,y+j)); } } } void gamma(T scal, double power) { int i,j; for (i=0;i<this->sizeX(); i++) for (j=0; j<this->sizeY(); j++) { hvColRGB<T> v = this->get(i,j); v.gamma(scal, power); this->update(i,j,v); } } void convert(const hvBitmap &pict, const hvColRGBA<T> &va, const hvColRGBA<T> &vb) { hvField2< hvColRGBA<T> >::reset(pict.sizeX(), pict.sizeY(), hvColRGBA<T>(0)); //hvArray2< hvColRGB<T> >::reset(pict.sizeX(), pict.sizeY(), hvColRGB<T>(0)); int i,j; for (i=0; i<pict.sizeX(); i++) for (j=0; j<pict.sizeY(); j++) { if (pict.get(i,j)) this->update(i,j,va); else this->update(i,j,vb); } } void loadPPM(FILE *fd, T norm, T alpha) { int sx, sy; int i,j, type; char buff[256]; hvColRGB<T> co; hvPictRGB<T>::readPPMLine(fd,buff); if (strcmp(buff,"P6\n")==0) type = 0; else if (strcmp(buff,"P3\n")==0) type = 1; else { type = 2; printf("unknown picture PPM type=%d (%s)\n", type,buff); } hvPictRGB<T>::readPPMLine(fd,buff); sscanf(buff,"%d %d",&sx,&sy); hvPictRGB<T>::readPPMLine(fd,buff); if (strcmp(buff,"255\n")!=0){ printf("type=%d\n", type); hvFatal("Not the right PPM Format"); } this->reset(sx, sy, hvColRGBA<T>()); for (i=0; i<sy; i++) for (j=0; j<sx; j++) { unsigned char r,g,b; if (type==0) { fread(&r,1,sizeof(unsigned char),fd); fread(&g,1,sizeof(unsigned char),fd); fread(&b,1,sizeof(unsigned char),fd); } else if (type==1) { int rr, gg, bb; fscanf(fd, "%d %d %d", &rr, &gg, &bb); r= (unsigned char)rr; g= (unsigned char)gg; b= (unsigned char)bb; } else { r=0; g=0; b=0; } hvArray2< hvColRGBA<T> >::update(j,sy-i-1,hvColRGBA<T>((T)r/norm, (T)g/norm, (T)b/norm, alpha)); } } void loadPPMA(FILE *fd, T norm) { int sx, sy; int i,j, type; char buff[256]; hvColRGB<T> co; hvPictRGB<T>::readPPMLine(fd,buff); if (strcmp(buff,"P6\n")==0) type = 0; else if (strcmp(buff,"P3\n")==0) type = 1; else { type = 2; printf("unknown picture PPM type=%d (%s)\n", type,buff); } hvPictRGB<T>::readPPMLine(fd,buff); sscanf(buff,"%d %d",&sx,&sy); hvPictRGB<T>::readPPMLine(fd,buff); if (strcmp(buff,"255\n")!=0){ printf("type=%d\n", type); hvFatal("Not the right PPM Format"); } this->reset(sx, sy, hvColRGBA<T>()); for (i=0; i<sy; i++) for (j=0; j<sx; j++) { unsigned char r,g,b,aa; if (type==0) { fread(&r,1,sizeof(unsigned char),fd); fread(&g,1,sizeof(unsigned char),fd); fread(&b,1,sizeof(unsigned char),fd); fread(&aa,1,sizeof(unsigned char),fd); } else if (type==1) { int rr, gg, bb, alpha; fscanf(fd, "%d %d %d %d", &rr, &gg, &bb, &alpha); r= (unsigned char)rr; g= (unsigned char)gg; b= (unsigned char)bb; aa = (unsigned char)alpha; } else { r=0; g=0; b=0; aa=0; } hvArray2< hvColRGBA<T> >::update(j,sy-i-1,hvColRGBA<T>((T)r/norm, (T)g/norm, (T)b/norm, (T)aa/norm)); } } void savePPM(FILE *fd, T norm, bool alpha=false) { int i,j; hvColRGBA<T> co; unsigned char v; fprintf(fd,"P6\n"); fprintf(fd,"%d %d\n", this->sizeX(), this->sizeY()); fprintf(fd,"255\n"); for (i=0; i<this->sizeY(); i++) for (j=0; j<this->sizeX(); j++) { co = hvArray2< hvColRGBA<T> >::get(j, this->sizeY()-i-1); v = (unsigned char)((T)(alpha?co.ALPHA():co.RED())*norm); fwrite(&v,1,sizeof(unsigned char),fd); v = (unsigned char)((T)(alpha?co.ALPHA():co.GREEN())*norm); fwrite(&v,1,sizeof(unsigned char),fd); v = (unsigned char)((T)(alpha?co.ALPHA():co.BLUE())*norm); fwrite(&v,1,sizeof(unsigned char),fd); } } void savePPMA(FILE *fd, T norm) { int i,j; hvColRGBA<T> co; unsigned char v; fprintf(fd,"P6\n"); fprintf(fd,"%d %d\n", this->sizeX(), this->sizeY()); fprintf(fd,"255\n"); for (i=0; i<this->sizeY(); i++) for (j=0; j<this->sizeX(); j++) { co = hvArray2< hvColRGBA<T> >::get(j, this->sizeY()-i-1); v = (unsigned char)((T)co.RED()*norm); fwrite(&v,1,sizeof(unsigned char),fd); v = (unsigned char)((T)co.GREEN()*norm); fwrite(&v,1,sizeof(unsigned char),fd); v = (unsigned char)((T)co.BLUE()*norm); fwrite(&v,1,sizeof(unsigned char),fd); v = (unsigned char)((T)co.ALPHA()*norm); fwrite(&v,1,sizeof(unsigned char),fd); } } }; } #endif // !efined(AFX_PICTRGB_H__098453F0_1C38_49E9_A6F4_AABF90AA55E8__INCLUDED_)
121,181
C++
.h
2,980
36.677181
283
0.576811
ASTex-ICube/semiproctex
39
8
2
LGPL-2.1
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,956
hvColor.h
ASTex-ICube_semiproctex/Semiproc_synthesis_Src/3rdParty/Externals/hview/hvColor.h
/* * Code author: Jean-Michel Dischler */ /** * @version 1.0 */ #if !defined(AFX_COLOR_H__098453F0_1C38_49E9_A6F4_AABF90AA55E8__INCLUDED_) #define AFX_COLOR_H__098453F0_1C38_49E9_A6F4_AABF90AA55E8__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include "hvVec3.h" namespace hview { // D65 reference white static const double Xn = 0.950456 ; static const double Yn = 1.0 ; static const double Zn = 1.088754 ; static const double un = 0.197832 ; static const double vn = 0.468340 ; template <class T> class hvColRGB : public hvVec3<T> { public: hvColRGB<T>() : hvVec3<T>() { } hvColRGB<T>(T r, T g, T b) : hvVec3<T>(r,g,b) { } hvColRGB<T>(T l) : hvVec3<T>(l) { } hvColRGB<T>(const hvVec3<T> &a): hvVec3<T>(a) { } template <class X> hvColRGB<T>(const hvColRGB<X> &c) { hvVec3<T> v; v.cast(hvVec3<X>(c)); *this = hvColRGB<T>(v); } operator hvVec3<T>() { return (hvVec3<T>)*this; } T RED() const { return hvVec3<T>::X(); } T GREEN() const { return hvVec3<T>::Y(); } T BLUE() const { return hvVec3<T>::Z(); } T luminance() const { return (T)(((double)hvVec3<T>::X()+(double)hvVec3<T>::Y()+(double)hvVec3<T>::Z())/3.0); } void torgbe(T scal, unsigned char rgbe[4]) { T v; int e; v = RED(); if (GREEN() > v) v = GREEN(); if (BLUE() > v) v = BLUE(); if ((float)v/(float)scal < 1e-32) { rgbe[0] = rgbe[1] = rgbe[2] = rgbe[3] = 0; } else { float vr = frexp((float)v/(float)scal,&e) * 256.0/((float)v/(float)scal); rgbe[0] = (unsigned char) ((float)RED()/(float)scal * vr); rgbe[1] = (unsigned char) ((float)GREEN()/(float)scal * vr); rgbe[2] = (unsigned char) ((float)BLUE()/(float)scal * vr); rgbe[3] = (unsigned char) (e + 128); } } void fromrgbe(T scal, unsigned char rgbe[4]) { float f; if (rgbe[3]!=0) { /*nonzero pixel*/ f = ldexp(1.0,rgbe[3]-(int)(128+8)); *this = hvColRGB( (T)((float)scal*f*(float)rgbe[0]), (T)((float)scal*f*(float)rgbe[1]),(T)((float)scal*f*(float)rgbe[2]) ); } else *this = hvColRGB(); } void tohsv(const hvColRGB<T> &rgb, T scal) { double min = (double)rgb.minCoord()/(double)scal; double max = (double)rgb.maxCoord()/(double)scal; double rr = (double)rgb.RED()/(double)scal; double gg = (double)rgb.GREEN()/(double)scal; double bb = (double)rgb.BLUE()/(double)scal; int t = 0; if (max!=min) { if (rgb.RED()>=rgb.GREEN() && rgb.RED()>=rgb.BLUE()) t = (int)(60.0*(gg-bb)/(max-min)+360.0) % 360; else if (rgb.GREEN()>=rgb.RED() && rgb.GREEN()>=rgb.BLUE()) t = (int)(60.0*(bb-rr)/(max-min)+120.0); else t = (int)(60.0*(rr-gg)/(max-min)+240.0); } double s = (max==0.0?0.0:1.0-min/max); double v = max; *this = hvColRGB((T)((double)t/360.0*(double)scal), (T)(s*(double)scal), (T)(v*(double)scal)); } void toxyz(const hvColRGB<T> &rgb, T scal) { double cx = 0.412453 * (double)rgb.RED()/(double)scal ; cx += 0.357580 * (double)rgb.GREEN()/(double)scal ; cx += 0.180423 * (double)rgb.BLUE()/(double)scal ; if (cx>1.0) cx=1.0; double cy = 0.212671 * (double)rgb.RED()/(double)scal ; cy += 0.715160 * (double)rgb.GREEN()/(double)scal ; cy += 0.072169 * (double)rgb.BLUE()/(double)scal ; if (cy>1.0) cy=1.0; double cz = 0.019334 * (double)rgb.RED()/(double)scal ; cz += 0.119193 * (double)rgb.GREEN()/(double)scal ; cz += 0.950227 * (double)rgb.BLUE()/(double)scal ; if (cz>1.0) cz=1.0; *this = hvColRGB((T)(cx*(double)scal), (T)(cy*(double)scal), (T)(cz*(double)scal)); } void fromxyz(const hvColRGB<T> &rgb, T scal) { double cx = 3.240479 * (double)rgb.RED()/(double)scal ; cx += -1.537150 * (double)rgb.GREEN()/(double)scal ; cx += -0.498535 * (double)rgb.BLUE()/(double)scal ; if (cx>1.0) cx=1.0; if (cx<0.0) cx=0.0; double cy = -0.969256 * (double)rgb.RED()/(double)scal ; cy += 1.875992 * (double)rgb.GREEN()/(double)scal ; cy += 0.041556 * (double)rgb.BLUE()/(double)scal ; if (cy>1.0) cy=1.0; if (cy<0.0) cy=0.0; double cz = 0.055648 * (double)rgb.RED()/(double)scal ; cz += -0.204043 * (double)rgb.GREEN()/(double)scal ; cz += 1.057311 * (double)rgb.BLUE()/(double)scal ; if (cz>1.0) cz=1.0; if (cz<0.0) cz=0.0; *this = hvColRGB((T)(cx*(double)scal), (T)(cy*(double)scal), (T)(cz*(double)scal)); } void toLuv(const hvColRGB<T> &rgb, T scal) { hvColRGB<T> xyz; xyz.toxyz(rgb,scal); double X=(double)xyz.RED()/(double)scal; double Y=(double)xyz.GREEN()/(double)scal; double Z=(double)xyz.BLUE()/(double)scal; double L,u,v; /*!< L in [0,100], u in [-83,175], v in [-134,108] */ double Ydiv = Y/Yn ; if (Ydiv > 0.008856) L = 116.0 * pow(Ydiv,1.0/3.0) - 16.0 ; else // near black L = 903.3 * Ydiv ; double den = X + 15.0 * Y + 3.0 * Z ; double u1 = (4.0 * X) / den ; double v1 = (9.0 * Y) / den ; u = 13.0*L * (u1 - un) ; v = 13.0*L * (v1 - vn) ; if (L<0.0) L=0.0; if (L>100.0) L=100.0; if (u<-83.0) u=-83.0; if (u>175.0) u=175.0; if (v<-134.0) u=-134.0; if (u>108.0) u=108.0; *this = hvColRGB((T)((L/100.0)*(double)scal), (T)((u+83.0)/(175.0+83.0)*(double)scal), (T)((v+134.0)/(108.0+134.0)*(double)scal)); } void fromLuv(const hvColRGB<T> &Luv, T scal) { double L = (double)Luv.RED()/(double)scal*100.0 ; double u = (double)Luv.GREEN()/(double)scal*(175.0+83.0)-83.0 ; double v = (double)Luv.BLUE()/(double)scal*(108.0+134.0)-134.0 ; double X,Y,Z; if (L > 8.0) Y = pow(((L+16.0) / 116.0),3.0) ; else // near black Y = Yn * L / 903.3 ; double den = 13.0 * L ; double u1 = u/den + un ; double v1 = v/den + vn ; den = 4.0*v1 ; X = Y * 9.0 * u1 / den ; Z = Y * (12.0 - 3.0*u1 - 20.0*v1) / den ; if (X<0.0) X=0.0; if (X>1.0) X=1.0; if (Y<0.0) Y=0.0; if (Y>1.0) Y=1.0; if (Z<0.0) Z=0.0; if (Z>1.0) Z=1.0; hvColRGB<T> xyz = hvColRGB((T)(X*(double)scal), (T)(Y*(double)scal), (T)(Z*(double)scal)); fromxyz(xyz,scal); } void clamp(T min, T max) { T r = hvVec3<T>::X(); if (r<min) r=min; else if (r>max) r=max; T g = hvVec3<T>::Y(); if (g<min) g=min; else if (g>max) g=max; T b = hvVec3<T>::Z(); if (b<min) b=min; else if (b>max) b=max; *this = hvColRGB(r, g, b); } void gammaNormalized(const hvColRGB<T> &max, T scal, double power) { double r = (double)hvVec3<T>::X()/(double)max.X(); if (r<0.0) r=0.0; else if (r>1.0) r=1.0; double g = (double)hvVec3<T>::Y()/(double)max.Y(); if (g<0.0) g=0.0; else if (g>1.0) g=1.0; double b = (double)hvVec3<T>::Z()/(double)max.Z(); if (b<0.0) b=0.0; else if (b>1.0) b=1.0; r = (double)scal*pow(r,power); g = (double)scal*pow(g,power); b = (double)scal*pow(b,power); *this = hvColRGB((T)r, (T)g, (T)b); } void gammaNormalizedMax(const hvColRGB<T> &max, T scal, double power) { double r = (double)hvVec3<T>::X()/(double)max.X(); if (r<0.0) r=0.0; else if (r>1.0) r=1.0; double g = (double)hvVec3<T>::Y()/(double)max.Y(); if (g<0.0) g=0.0; else if (g>1.0) g=1.0; double b = (double)hvVec3<T>::Z()/(double)max.Z(); if (b<0.0) b=0.0; else if (b>1.0) b=1.0; r = (double)scal*pow(r,power); g = (double)scal*pow(g,power); b = (double)scal*pow(b,power); //if (r>=g && r>=b) *this = hvColRGB((T)r, (T)r, (T)r); //else if (g>=r && g>=b) *this = hvColRGB((T)g, (T)g, (T)g); //else *this = hvColRGB((T)b, (T)b, (T)b); *this = hvColRGB((T)r, (T)g, (T)b); } void gammaClampedMax(const hvColRGB<T> &max, T scal, double thresh) { double r = (double)hvVec3<T>::X() / (double)max.X(); if (r<0.0) r = 0.0; else if (r>1.0) r = 1.0; double g = (double)hvVec3<T>::Y() / (double)max.Y(); if (g<0.0) g = 0.0; else if (g>1.0) g = 1.0; double b = (double)hvVec3<T>::Z() / (double)max.Z(); if (b<0.0) b = 0.0; else if (b>1.0) b = 1.0; if (r < thresh) r = 0.0; else r = (double)scal*r; if (g < thresh) g = 0.0; else g = (double)scal*g; if (b < thresh) b = 0.0; else b = (double)scal*b; //if (r>=g && r>=b) *this = hvColRGB((T)r, (T)r, (T)r); //else if (g>=r && g>=b) *this = hvColRGB((T)g, (T)g, (T)g); //else *this = hvColRGB((T)b, (T)b, (T)b); *this = hvColRGB((T)r, (T)g, (T)b); } void gamma(T scal, double power) { double r = (double)hvVec3<T>::X()/(double)scal; if (r<0.0) r=0.0; else if (r>1.0) r=1.0; double g = (double)hvVec3<T>::Y()/(double)scal; if (g<0.0) g=0.0; else if (g>1.0) g=1.0; double b = (double)hvVec3<T>::Z()/(double)scal; if (b<0.0) b=0.0; else if (b>1.0) b=1.0; r = (double)scal*pow(r,power); g = (double)scal*pow(g,power); b = (double)scal*pow(b,power); *this = hvColRGB((T)r, (T)g, (T)b); } void blend(const hvColRGB<T> &c1, const hvColRGB<T> &c2, T scal, double alpha) { double r = (double)scal*((double)c1.RED()/(double)scal*alpha+(double)c2.RED()/(double)scal*(1.0-alpha)); double g = (double)scal*((double)c1.GREEN()/(double)scal*alpha+(double)c2.GREEN()/(double)scal*(1.0-alpha)); double b = (double)scal*((double)c1.BLUE()/(double)scal*alpha+(double)c2.BLUE()/(double)scal*(1.0-alpha)); *this = hvColRGB((T)r, (T)g, (T)b); } void blend(const hvColRGB<T> &c1, const hvColRGB<T> &c2, double alpha) { double r = (double)c1.RED()*alpha+(double)c2.RED()*(1.0-alpha); double g = (double)c1.GREEN()*alpha+(double)c2.GREEN()*(1.0-alpha); double b = (double)c1.BLUE()*alpha+(double)c2.BLUE()*(1.0-alpha); *this = hvColRGB((T)r, (T)g, (T)b); } void add(const hvColRGB<T> &a, const hvColRGB<T> &b) { hvVec3<T>::add((hvVec3<T>)a,(hvVec3<T>)b); } hvColRGB<T> operator+(const hvColRGB<T> &b) const { hvVec3<T>::operator+((hvVec3<T>)b); return *this; } void operator+=(const hvColRGB<T> &b) { hvVec3<T>::operator+=((hvVec3<T>)b); } void sub(const hvColRGB<T> &a, const hvColRGB<T> &b) { hvVec3<T>::sub((hvVec3<T>)a,(hvVec3<T>)b); } hvColRGB<T> operator-(const hvColRGB<T> &b) const { hvVec3<T>::operator-((hvVec3<T>)b); return *this; } void operator-=(const hvColRGB<T> &b) { hvVec3<T>::operator-=((hvVec3<T>)b); } void subabs(const hvColRGB<T> &a, const hvColRGB<T> &b) { *this = hvColRGB( a.RED()<b.RED()?b.RED()-a.RED():a.RED()-b.RED(), a.GREEN()<b.GREEN()?b.GREEN()-a.GREEN():a.GREEN()-b.GREEN(), a.BLUE()<b.BLUE()?b.BLUE()-a.BLUE():a.BLUE()-b.BLUE() ); } void mult(const hvColRGB<T> &a, const hvColRGB<T> &b) { hvVec3<T>::mult((hvVec3<T>)a,(hvVec3<T>)b); } hvColRGB<T> operator*(const hvColRGB<T> &b) const { hvVec3<T>::operator*((hvVec3<T>)b); return *this; } void operator*=(const hvColRGB<T> &b) { hvVec3<T>::operator*=((hvVec3<T>)b); } template <class X> void operator*=(X v) { hvVec3<T>::x= (T)((X)hvVec3<T>::x*v); hvVec3<T>::y=(T)((X)hvVec3<T>::y*v); hvVec3<T>::z=(T)((X)hvVec3<T>::z*v); } void div(const hvColRGB<T> &a, const hvColRGB<T> &b) { hvVec3<T>::div((hvVec3<T>)a,(hvVec3<T>)b); } hvColRGB<T> operator/(const hvColRGB<T> &b) const { hvVec3<T>::operator/((hvVec3<T>)b); return *this; } void operator/=(const hvColRGB<T> &b) { hvVec3<T>::operator/=((hvVec3<T>)b); } template <class X> void operator/=(X v) { hvVec3<T>::x= (T)((X)hvVec3<T>::x/v); hvVec3<T>::y=(T)((X)hvVec3<T>::y/v); hvVec3<T>::z=(T)((X)hvVec3<T>::z/v); } //void operator/=(T v) { x= (T)(x/v); y=(T)(y/v); z=(T)(z/v); } void scale(const hvColRGB<T> &a, T k) { hvVec3<T>::scale((hvVec3<T>)a,k); } template <class X> void scale(X v) { hvVec3<T>::x= (T)((X)hvVec3<T>::x*v); hvVec3<T>::y=(T)((X)hvVec3<T>::y*v); hvVec3<T>::z=(T)((X)hvVec3<T>::z*v); } void square() { hvVec3<T>::square(); } bool equals(const hvColRGB<T> &a) const { return hvVec3<T>::equals((hvVec3<T>)a); } bool operator==(const hvColRGB<T> &a) const { return hvVec3<T>::equals((hvVec3<T>)a); } void difference(const hvColRGB<T> &c1, const hvColRGB<T> &c2) { double r = (double)c1.RED()-(double)c2.RED(); if (r<0.0) r=-r; double g = (double)c1.GREEN()-(double)c2.GREEN(); if (g<0.0) g=-g; double b = (double)c1.BLUE()-(double)c2.BLUE(); if (b<0.0) b=-b; *this = hvColRGB((T)r, (T)g, (T)b); } void difference(const hvColRGB<T> &c1, const hvColRGB<T> &c2, double scale, double offset) { double r = (double)c1.RED()-(double)c2.RED()+offset; if (r<0.0) r=0.0; else if (r>=2.0*scale) r = 2.0*scale-1.0; double g = (double)c1.GREEN()-(double)c2.GREEN()+offset; if (g<0.0) g=0.0; else if (g>=2.0*scale) g = 2.0*scale-1.0; double b = (double)c1.BLUE()-(double)c2.BLUE()+offset; if (b<0.0) b=0.0; else if (b>=2.0*scale) b = 2.0*scale-1.0; *this = hvColRGB((T)r, (T)g, (T)b); } double squaredDifferenceChroma(const hvColRGB<T> &c2) { hvColRGB<unsigned char> cl1; cl1.toLuv(*this, 255.0); hvColRGB<unsigned char> cl2; cl2.toLuv(c2, 255.0); double g = (double)cl1.GREEN()-(double)cl2.GREEN(); double b = (double)cl1.BLUE()-(double)cl2.BLUE(); return g*g+b*b; } double squaredDifference(const hvColRGB<T> &c2) { double r = (double)RED()-(double)c2.RED(); double g = (double)GREEN()-(double)c2.GREEN(); double b = (double)BLUE()-(double)c2.BLUE(); return r*r+g*g+b*b; } double squaredDifferenceNorm(double scal, const hvColRGB<T> &c2) { double r = (double)RED()/scal-(double)c2.RED()/scal; double g = (double)GREEN()/scal-(double)c2.GREEN()/scal; double b = (double)BLUE()/scal-(double)c2.BLUE()/scal; return r*r+g*g+b*b; } void keepMin(const hvColRGB<T> &v1, const hvColRGB<T> &v2) { hvVec3<T>::keepMin((hvVec3<T>)v1, (hvVec3<T>)v2); } void keepMax(const hvColRGB<T> &v1, const hvColRGB<T> &v2) { hvVec3<T>::keepMax((hvVec3<T>)v1, (hvVec3<T>)v2); } void normalize(const hvColRGB<T> &min, const hvColRGB<T> &max, double scal) { double r = (double)RED(); r = scal*(r-(double)min.RED())/((double)max.RED()-(double)min.RED()); double g = (double)GREEN(); g = scal*(g-(double)min.GREEN())/((double)max.GREEN()-(double)min.GREEN()); double b = (double)BLUE(); b = scal*(b-(double)min.BLUE())/((double)max.BLUE()-(double)min.BLUE()); *this = hvColRGB((T)r, (T)g, (T)b); } void mean(int n, hvColRGB<T> cc[]) { double r=0.0, g=0.0, b=0.0; for (int i=0; i<n; i++) { r += (double)cc[i].RED(); g += (double)cc[i].GREEN(); b += (double)cc[i].BLUE(); } *this = hvColRGB((T)(r/(double)n), (T)(g/(double)n), (T)(b/(double)n)); } //T maxCoord() const { return hvVec3<T>::maxCoord(); } }; template <class T> class hvColRGBA : public hvColRGB<T> { protected: T a; public: hvColRGBA<T>() : hvColRGB<T>(),a(T(0)) { } hvColRGBA<T>(T r, T g, T b) : hvColRGB<T>(r,g,b),a(T(0)) { } hvColRGBA<T>(T r, T g, T b, T alpha) : hvColRGB<T>(r,g,b), a(alpha) { } hvColRGBA<T>(T l) : hvColRGB<T>(l),a(T(0)) { } hvColRGBA<T>(const hvColRGB<T> &c, T alpha) : hvColRGB<T>(c), a(alpha) { } //template <class X> hvColRGBA<T>(const hvColRGBA<X> &c) { *this = hvColRGB<T>(hvColRGB<X>(c)); a=T(c.a); } T ALPHA() const { return a; } void setAlpha(T aa) { a = aa; } void operator*=(const hvColRGBA<T> &b) { hvVec3<T>::operator*=((hvVec3<T>)b); } void operator/=(const hvColRGBA<T> &b) { hvVec3<T>::operator/=((hvVec3<T>)b); } void interpolate(const hvColRGBA<T> &c1, const hvColRGBA<T> &c2, double alpha) { double r = (double)c1.RED()*(1.0-alpha)+(double)c2.RED()*alpha; double g = (double)c1.GREEN()*(1.0-alpha)+(double)c2.GREEN()*alpha; double b = (double)c1.BLUE()*(1.0-alpha)+(double)c2.BLUE()*alpha; double a = (double)c1.ALPHA()*(1.0-alpha)+(double)c2.ALPHA()*alpha; *this = hvColRGBA((T)r, (T)g, (T)b, (T)a); } void mix(const hvColRGBA<T> &c1, const hvColRGBA<T> &c2, T scal, double alpha) { double r = (double)scal*((double)c1.RED()/(double)scal*alpha+(double)c2.RED()/(double)scal*(1.0-alpha)); double g = (double)scal*((double)c1.GREEN()/(double)scal*alpha+(double)c2.GREEN()/(double)scal*(1.0-alpha)); double b = (double)scal*((double)c1.BLUE()/(double)scal*alpha+(double)c2.BLUE()/(double)scal*(1.0-alpha)); double aa = (double)scal*((double)c1.ALPHA()/(double)scal*alpha+(double)c2.ALPHA()/(double)scal*(1.0-alpha)); *this = hvColRGBA((T)r, (T)g, (T)b, (T)aa); } void mix(const hvColRGBA<T> &c1, const hvColRGBA<T> &c2, double alpha) { double r = (double)c1.RED()*alpha+(double)c2.RED()*(1.0-alpha); double g = (double)c1.GREEN()*alpha+(double)c2.GREEN()*(1.0-alpha); double b = (double)c1.BLUE()*alpha+(double)c2.BLUE()*(1.0-alpha); double aa = (double)c1.ALPHA()*alpha+(double)c2.ALPHA()*(1.0-alpha); *this = hvColRGBA((T)r, (T)g, (T)b, (T)aa); } }; } #endif // !defined(AFX_COLOR_H__098453F0_1C38_49E9_A6F4_AABF90AA55E8__INCLUDED_)
16,203
C++
.h
351
43.447293
156
0.602112
ASTex-ICube/semiproctex
39
8
2
LGPL-2.1
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,957
hvArray2.h
ASTex-ICube_semiproctex/Semiproc_synthesis_Src/3rdParty/Externals/hview/hvArray2.h
/* * Code author: Jean-Michel Dischler */ /** * @version 1.0 */ #if !defined(AFX_ARRAY2_H__164A3508_C961_4D87_AD7A_9D43051600EA__INCLUDED_) #define AFX_ARRAY2_H__164A3508_C961_4D87_AD7A_9D43051600EA__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include "hvError.h" #include <cassert> namespace hview { template <class T> class hvArray2 { protected: T *t; int sx, sy; public: hvArray2() { t=0; sx=0; sy=0; } hvArray2(int x, int y, T nil) { t = new T[x*y]; if (t==0) { sx=-1; sy=1; return; } for (int i=0; i<x*y; i++) t[i]=nil; sx = x; sy = y; } T *data() const { return t; } // copy hvArray2(const hvArray2 &a) { hvFatal("no temporary creation of hvArray2!"); } // affectation hvArray2 &operator=(hvArray2 &a) { if (this != &a) { if (t!=0) delete [] t; if (a.isInvalid()) { sx=-1; sy=1; t=0; return *this; } sx = a.sx; sy = a.sy; t = new T [sx*sy]; if (t==0) { sx=-1; sy=1; return *this; } for (int i=0; i<sx*sy; i++) t[i]=a.t[i]; } return *this; } // affectation void clone(const hvArray2 &a) { if (t!=0) delete [] t; if (a.isInvalid()) { sx=-1; sy=1; t=0; return; } sx = a.sx; sy = a.sy; t = new T [sx*sy]; if (t==0) { sx=-1; sy=1; return; } for (int i=0; i<sx*sy; i++) t[i]=a.t[i]; } // isInvalid bool isInvalid() const { return sx==-1; } // isVoid bool isVoid() const { return t==0; } // operations void clear(T nil) { for (int i=0; i<sx*sy; i++) t[i]=nil; } // selectors int sizeX()const { return sx; } int sizeY()const { return sy; } int maxLevels() { int nn=sx<sy?sy:sx; int ll=0; while(nn!=1) { nn/=2; ll++; } return ll; } void reset(int x, int y, T nil) { //printf("in reset %d\n", t); if (t!=0) { delete [] t; } t = new T[x*y]; //printf("allocation %d\n", t); if (t==0) { sx=-1; return; } for (int i=0; i<x*y; i++) t[i]=nil; sx = x; sy = y; } void reset(int x, int y) { if (t!=0) delete [] t; t = new T[x*y]; if (t==0) { sx=-1; return; } sx = x; sy = y; } void reset() { if (t!=0) delete [] t; t=0; sx=0; sy=0; } T get(int x, int y) const { assert(!(x < 0 || x >= sx || y < 0 || y >= sy)); assert(t != NULL); return t[x+y*sx]; } void update(int x, int y, T val) { assert(!(x < 0 || x >= sx || y < 0 || y >= sy)); assert(t != NULL); t[x+y*sx]=val; } ~hvArray2() { if (t!=0) delete [] t; } }; } #endif // !defined(AFX_ARRAY2_H__164A3508_C961_4D87_AD7A_9D43051600EA__INCLUDED_)
2,505
C++
.h
126
17.357143
81
0.558337
ASTex-ICube/semiproctex
39
8
2
LGPL-2.1
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,960
hvNoise.h
ASTex-ICube_semiproctex/Semiproc_synthesis_Src/3rdParty/Externals/hview/hvNoise.h
/* * Code author: Jean-Michel Dischler */ /** * @version 1.0 */ #ifndef _HV_NOISE_H_ #define _HV_NOISE_H_ //#define SINC //////////////////////////////////////////// /* Noise: is a function returning a pseudo-random value between -1 and 1. */ //////////////////////////////////////////// //////////////////////////////////////////// #include "hvLinearTransform3.h" #include "hvPair.h" #define INTERPOL(s,v0,v1) ((v0)+(s)*((v1)-(v0))) #define FASTFLOOR(x) ( ((x)>0) ? ((int)x) : (((int)x)-1) ) #define F2 0.366025403 // F2 = 0.5*(sqrt(3.0)-1.0) #define G2 0.211324865 // G2 = (3.0-Math.sqrt(3.0))/6.0 // Simple skewing factors for the simplex 3D case #define F3 0.333333333 #define G3 0.166666667 // The skewing and unskewing factors are hairy again for the 4D case #define F4 0.309016994 // F4 = (Math.sqrt(5.0)-1.0)/4.0 #define G4 0.138196601 // G4 = (5.0-Math.sqrt(5.0))/20.0 namespace hview { const int MAX_NOISE_RAND=1024; const int WAVELETNOISE_SIZE=512; typedef struct { double x, y, z; } hvnoise_vec; class hvNoise { public: static double rnd_tab[MAX_NOISE_RAND]; static unsigned int P[MAX_NOISE_RAND]; static hvnoise_vec G[MAX_NOISE_RAND]; static unsigned char perm[512]; static int phi(int x) { x = x%MAX_NOISE_RAND; if (x<0) x=x+MAX_NOISE_RAND; return(P[x]); } static void gamma(int i,int j,int k,hvVec3<double> *v,double *val) { int index; index=phi(i+phi(j+phi(k))); *v = hvVec3<double>(G[index].x,G[index].y,G[index].z) ; *val = rnd_tab[index]; } static double omega(int i,int j,int k,double x,double y,double z) { register double u,v,w; double val; hvVec3<double> vec,vec2; u = (x>0.0?x:-x); v=(y>0.0?y:-y); w=(z>0.0?z:-z); u= (u<1.0)? u*u*(2.0*u-3.0)+1.0 : 0.0; v= (v<1.0)? v*v*(2.0*v-3.0)+1.0 : 0.0; w= (w<1.0)? w*w*(2.0*w-3.0)+1.0 : 0.0; vec = hvVec3<double>(x,y,z); gamma(i,j,k,&vec2,&val); return(u*v*w*(vec.dot(vec2)+val)); } static double grad1( int hash, double x ) { int h = hash & 15; double grad = 1.0f + (h & 7); // Gradient value 1.0, 2.0, ..., 8.0 if (h&8) grad = -grad; // Set a random sign for the gradient return ( grad * x ); // Multiply the gradient with the distance } static double grad2( int hash, double x, double y ) { int h = hash & 7; // Convert low 3 bits of hash code double u = h<4 ? x : y; // into 8 simple gradient directions, double v = h<4 ? y : x; // and compute the dot product with (x,y). return ((h&1)? -u : u) + ((h&2)? -2.0f*v : 2.0f*v); } static double grad3( int hash, double x, double y , double z ) { int h = hash & 15; // Convert low 4 bits of hash code into 12 simple double u = h<8 ? x : y; // gradient directions, and compute dot product. double v = h<4 ? y : h==12||h==14 ? x : z; // Fix repeats at h = 12 to 15 return ((h&1)? -u : u) + ((h&2)? -v : v); } static double grad4( int hash, double x, double y, double z, double t ) { int h = hash & 31; // Convert low 5 bits of hash code into 32 simple double u = h<24 ? x : y; // gradient directions, and compute dot product. double v = h<16 ? y : z; double w = h<8 ? z : t; return ((h&1)? -u : u) + ((h&2)? -v : v) + ((h&4)? -w : w); } public: static double gnoise(double x,double y,double z) { int i,j,k; double ix,iy,iz; ix=floor(x); iy=floor(y); iz=floor(z); i=(int)ix; j=(int)iy; k=(int)iz; double vv= omega(i,j,k,x-ix,y-iy,z-iz)+ omega(i,j,k+1,x-ix,y-iy,z-(iz+1.0))+ omega(i,j+1,k,x-ix,y-(iy+1.0),z-iz)+ omega(i,j+1,k+1,x-ix,y-(iy+1.0),z-(iz+1.0))+ omega(i+1,j,k,x-(ix+1.0),y-iy,z-iz)+ omega(i+1,j,k+1,x-(ix+1.0),y-iy,z-(iz+1.0))+ omega(i+1,j+1,k,x-(ix+1.0),y-(iy+1.0),z-iz)+ omega(i+1,j+1,k+1,x-(ix+1.0),y-(iy+1.0),z-(iz+1.0)); return vv/4.0; } static double inoise(int ix,int iy, int iz) { return(rnd_tab[(phi(ix)+3*phi(iy)+5*phi(iz))%MAX_NOISE_RAND]); } static double cnoise2D(double x, double y) { double vx0, vx1, vy0, vy1; int ix, iy; double sx, sy; double rt; ix = (int)floor(x); x -= ix; iy = (int)floor(y); y -= iy; sx = x*x*(3.0 - 2.0*x); sy = y*y*(3.0 - 2.0*y); vy0 = inoise(ix, iy, 0); vy1 = inoise(ix, iy + 1, 0); vx0 = INTERPOL(sy, vy0, vy1); vy0 = inoise(ix + 1, iy, 0); vy1 = inoise(ix + 1, iy + 1, 0); vx1 = INTERPOL(sy, vy0, vy1); rt = INTERPOL(sx, vx0, vx1); return(rt); } static double cnoise(double x,double y,double z) { double vx0,vx1,vy0,vy1,vz0,vz1; int ix,iy,iz; double sx,sy,sz; double rt; ix = (int)floor(x); x -= ix; iy = (int)floor(y); y -= iy; iz = (int)floor(z); z -= iz; sx = x*x*(3.0-2.0*x); sy = y*y*(3.0-2.0*y); sz = z*z*(3.0-2.0*z); vz0 = inoise(ix,iy,iz); vz1 = inoise(ix,iy,iz+1); vy0 = INTERPOL(sz,vz0,vz1); vz0 = inoise(ix,iy+1,iz); vz1 = inoise(ix,iy+1,iz+1); vy1 = INTERPOL(sz,vz0,vz1); vx0 = INTERPOL(sy,vy0,vy1); vz0 = inoise(ix+1,iy,iz); vz1 = inoise(ix+1,iy,iz+1); vy0 = INTERPOL(sz,vz0,vz1); vz0 = inoise(ix+1,iy+1,iz); vz1 = inoise(ix+1,iy+1,iz+1); vy1 = INTERPOL(sz,vz0,vz1); vx1 = INTERPOL(sy,vy0,vy1); rt = INTERPOL(sx,vx0,vx1); return(rt); } static double turbulence(double x,double y,double z,double pix) { double t,scale,n; t=0.0; scale=1.0; while(scale>pix) { n=scale*gnoise(x/scale,y/scale,z/scale); t+=(n>0.0?n:-n); scale/=2.0; } return(0.8*t); } static double turbulence(double x, double y, double z, float ampli[], int nn) { double t, scale, n; t = 0.0; scale = 1.0; for (int i = 0; i<nn; i++) { n = ampli[i]*gnoise(x / scale, y / scale, z / scale); t += (n>0.0 ? n : -n); scale /= 3.0; } return(t); } static double turbulence(double x, double y, double z, double power, int nn) { double t, scale, n; t = 0.0; scale = 1.0; for (int i=0; i<nn; i++) { n = scale*gnoise(x / scale, y / scale, z / scale); t += (n>0.0 ? n : -n); scale /= power; } return(0.8*t); } hvNoise() { } virtual int dimension() const { return 2; } virtual double operator()(double ind[]) const { return hvNoise::turbulence(ind[0], ind[1], 5.78, 0.000001); } virtual double get(double ind[]) const { return hvNoise::turbulence(ind[0], ind[1], 5.78, 0.000001); } //static unsigned int seed; static void seeding(unsigned int x, unsigned int y, unsigned int z, unsigned int &seed ) //{ seed=x%unsigned int(1024)+(y%unsigned int(1024))*unsigned int(1024)+(z%unsigned int(1024))*unsigned int(1024*1024); } { seed=phi(x+phi(y+phi(z)))%(unsigned int)(1<<15)+(phi(3*x+phi(4*y+phi(z)))%(unsigned int)(1<<15))*(unsigned int)(1<<15); } static float next(unsigned int &seed) { seed *= (unsigned int)(3039177861); float res=(float)((double(seed)/4294967296.0)*2.0-1.0); return res; } ////////////////////////////////////////// // SINCNOISE static float sinc(float x) { if (x==0.0f) return 1.0f; else if (x<-8.0 || x>8.0) return 0.0; return (float)sin(M_PI*x)/M_PI/x; } static int Mod(int x, int n) {int m=x%n; return (m<0) ? m+n : m;} #define ARAD 16 #define MAX_NEIGH_CELLS 9 typedef enum { REGULAR, IRREGULAR, CROSS, BISQUARE, IRREGULARX, IRREGULARY, APAVEMENT } tilingtype; static int pave(float xp, float yp, // pavement parameters int Nx, float randx, float randy, float cx[MAX_NEIGH_CELLS], float cy[MAX_NEIGH_CELLS], float dx[MAX_NEIGH_CELLS], float dy[MAX_NEIGH_CELLS]) { unsigned int seed; int i, j; int nc = 0; float x = xp; float y = yp; int ix = (int)floor(x); float xx = x - (float)ix; int iy = (int)floor(y); float yy = y - (float)iy; for (j = -1; j <= 1; j++) for (i = -1; i <= 1; i++) { float rxi, rxs, ryi, rys; float ivpx = (float)ix + (float)i; float ivpy = (float)iy + (float)j; float decalx = (float)((int)ivpy%Nx) / (float)Nx; seeding((unsigned int)(ivpx + 5), (unsigned int)(ivpy + 10), 0, seed); rxi = next(seed)*randx*0.5f; //printf("rx %d,%d=%g, ", (unsigned int)(ivpx + 5), (unsigned int)(ivpy + 10), rx); seeding(3, (unsigned int)(ivpy + 10), 0, seed); ryi = next(seed)*randy*0.5f; seeding((unsigned int)(ivpx + 1 + 5), (unsigned int)(ivpy + 10), 0, seed); rxs = next(seed)*randx*0.5f; //printf("rxs %d,%d=%g\n", (unsigned int)(ivpx +1 + 5), (unsigned int)(ivpy + 10), rxs); seeding(3, (unsigned int)(ivpy + 1 + 10), 0, seed); rys = next(seed)*randy*0.5f; dx[nc] = (0.5f*(rxs + 1.0f - rxi)); dy[nc] = 0.5f*(rys + 1.0f - ryi); cx[nc] = (ivpx + decalx + rxi + dx[nc]); cy[nc] = ivpy + ryi + dy[nc]; nc++; } return nc; } static int paveb(float x, float y, // pavement parameters float cx[MAX_NEIGH_CELLS], float cy[MAX_NEIGH_CELLS], float dx[MAX_NEIGH_CELLS], float dy[MAX_NEIGH_CELLS]) { int i, j; int nc = 0; int ii, jj; int ix = (int)floor(x); float xx = x - (float)ix; int iy = (int)floor(y); float yy = y - (float)iy; int qx = (int)(xx*(int)5); int qy = (int)(yy*(int)5); for (i = 0; i < 3; i++) for (j = 0; j < 3; j++) { if (qx >= -2 + i * 2 + j && qx <= -2 + i * 2 + 1 + j && qy >= 1 - i + 2 * j && qy <= 1 - i + 2 * j + 1) { for (ii = 0; ii <= 2; ii++) for (jj = 0; jj <= 2; jj++) { if (ii == 1 || jj == 1) { int rx = -2 + i * 2 + j - 3 + ii * 2 + jj; int ry = 1 - i + 2 * j - 1 + jj * 2 - ii; dx[nc] = 1.0 / 5.0; dy[nc] = 1.0 / 5.0; cx[nc] = (float)ix + (float)rx / 5.0 + 1.0 / 5.0; cy[nc] = (float)iy + (float)ry / 5.0 + 1.0 / 5.0; nc++; } } int rx = -2 + i * 2 + j; int ry = 1 - i + 2 * j; dx[nc] = 0.5 / 5.0; dy[nc] = 0.5 / 5.0; cx[nc] = (float)ix + (float)(rx - 1) / 5.0 + 0.5 / 5.0; cy[nc] = (float)iy + (float)ry / 5.0 + 0.5 / 5.0; nc++; dx[nc] = 0.5 / 5.0; dy[nc] = 0.5 / 5.0; cx[nc] = (float)ix + (float)rx / 5.0 + 0.5 / 5.0; cy[nc] = (float)iy + (float)(ry + 2) / 5.0 + 0.5 / 5.0; nc++; dx[nc] = 0.5 / 5.0; dy[nc] = 0.5 / 5.0; cx[nc] = (float)ix + (float)(rx + 2) / 5.0 + 0.5 / 5.0; cy[nc] = (float)iy + (float)(ry + 1) / 5.0 + 0.5 / 5.0; nc++; dx[nc] = 0.5 / 5.0; dy[nc] = 0.5 / 5.0; cx[nc] = (float)ix + (float)(rx + 1) / 5.0 + 0.5 / 5.0; cy[nc] = (float)iy + (float)(ry - 1) / 5.0 + 0.5 / 5.0; nc++; //printf("anc=%d\n", nc); return nc; } } for (i = 0; i < 3; i++) for (j = 0; j < 2; j++) { if (qx == i * 2 + j && qy == 2 + 2 * j - i) { dx[nc] = 0.5 / 5.0; dy[nc] = 0.5 / 5.0; cx[nc] = (float)ix + (float)qx / 5.0 + dx[nc]; cy[nc] = (float)iy + (float)qy / 5.0 + dy[nc]; nc++; dx[nc] = 0.5 / 5.0; dy[nc] = 0.5 / 5.0; cx[nc] = (float)ix + (float)(qx - 2) / 5.0 + dx[nc]; cy[nc] = (float)iy + (float)(qy + 1) / 5.0 + dy[nc]; nc++; dx[nc] = 0.5 / 5.0; dy[nc] = 0.5 / 5.0; cx[nc] = (float)ix + (float)(qx + 1) / 5.0 + dx[nc]; cy[nc] = (float)iy + (float)(qy + 2) / 5.0 + dy[nc]; nc++; dx[nc] = 0.5 / 5.0; dy[nc] = 0.5 / 5.0; cx[nc] = (float)ix + (float)(qx - 1) / 5.0 + dx[nc]; cy[nc] = (float)iy + (float)(qy - 2) / 5.0 + dy[nc]; nc++; dx[nc] = 0.5 / 5.0; dy[nc] = 0.5 / 5.0; cx[nc] = (float)ix + (float)(qx + 2) / 5.0 + dx[nc]; cy[nc] = (float)iy + (float)(qy - 1) / 5.0 + dy[nc]; nc++; dx[nc] = 1.0 / 5.0; dy[nc] = 1.0 / 5.0; cx[nc] = (float)ix + (float)(qx - 2) / 5.0 + dx[nc]; cy[nc] = (float)iy + (float)(qy - 1) / 5.0 + dy[nc]; nc++; dx[nc] = 1.0 / 5.0; dy[nc] = 1.0 / 5.0; cx[nc] = (float)ix + (float)(qx - 1) / 5.0 + dx[nc]; cy[nc] = (float)iy + (float)(qy + 1) / 5.0 + dy[nc]; nc++; dx[nc] = 1.0 / 5.0; dy[nc] = 1.0 / 5.0; cx[nc] = (float)ix + (float)(qx + 1) / 5.0 + dx[nc]; cy[nc] = (float)iy + (float)(qy) / 5.0 + dy[nc]; nc++; dx[nc] = 1.0 / 5.0; dy[nc] = 1.0 / 5.0; cx[nc] = (float)ix + (float)(qx) / 5.0 + dx[nc]; cy[nc] = (float)iy + (float)(qy - 2) / 5.0 + dy[nc]; nc++; //printf("bnc=%d\n", nc); return nc; } } printf("error in paveb!!!\n"); return 0; } static int pavec(float x, float y, // pavement parameters float cx[9], float cy[9], float dx[9], float dy[9]) { float sx[9][9] = { {1.0, 1.5, 0.5, 1.0, 0.5, 0.5, 1.0, 0.5, 1.0 }, {1.5,0.5,0.5,1.0,0.5,1.0,0.5,1.0,1.0}, {0.5,1.5,1.0,1.0,0.5,0.5,1.5,1.0,1.0}, {1.0,1.0,1.5,0.5,1.5,1.0,0.5,0.5,0.5}, {0.5,1.0,1.0,0.5,0.5,1.0,1.5,1.5,1.5}, {0.5,1.0,0.5,0.5,1.5,1.0,1.0,1.5,1.0}, {1.0,0.5,1.0,0.5,0.5,1.5,1.0,1.0,1.0}, {0.5,1.0,1.0,1.0,1.5,0.5,0.5,0.5,1.0}, {1.0,1.0,1.5,0.5,1.5,1.0,0.5,0.5,0.5} }; float sy[9][9] = { {1.0, 0.5, 1.0, 0.5, 0.5, 1.0, 0.5, 1.0, 0.5 }, {0.5,1.0,1.0,0.5,1.0,0.5,0.5,1.0,0.5}, {1.0,0.5,0.5,1.0,0.5,1.0,0.5,0.5,1.0}, {0.5,1.0,0.5,1.0,0.5,1.0,1.0,0.5,1.0}, {0.5,1.0,0.5,1.0,1.0,0.5,0.5,0.5,0.5}, {1.0,1.0,0.5,1.0,0.5,0.5,1.0,0.5,0.5}, {0.5,1.0,1.0,0.5,1.0,0.5,0.5,0.5,0.5}, {1.0,0.5,1.0,0.5,0.5,1.0,0.5,1.0,0.5}, {0.5,1.0,0.5,1.0,0.5,1.0,1.0,0.5,1.0} }; float ddx[9][9] = { { 1.0, 0.0, 3.0, 3.0, 3.0, 3.0, 1.0, 0.0, -1.0 }, {0.0,-1.0,0.0,1.0,3.0,3.0,3.0,1.0,-1.0}, {3.0, 0.0,1.0,1.0,3.0,4.0,4.0,3.0,1.0}, {3.0,1.0,0.0,3.0,4.0,5.0,4.0,3.0,4.0}, {3.0,1.0,3.0,4.0,3.0,1.0,0.0,4.0,0.0}, {3.0,1.0,3.0,4.0,4.0,3.0,1.0,0.0,1.0}, {1.0,0.0,1.0,3.0,3.0,0.0,-1.0,3.0,3.0}, {0.0,-1.0,1.0,1.0,0.0,-1.0,-1.0,-1.0,-1.0}, {-1.0,-3.0,-4.0,-1.0,0.0,1.0,0.0,-1.0,-1.0} }; float ddy[9][9] = { { 1.0, 3.0, 3.0, 2.0, 1.0, -1.0, 0.0, 0.0, 2.0 }, {3.0, 3.0,4.0,4.0,3.0,2.0,1.0,1.0,2.0}, {3.0, 3.0,4.0,5.0,5.0,4.0,3.0,2.0,1.0}, {2.0,1.0,3.0,3.0,3.0,1.0,0.0,1.0,4.0}, {1.0,1.0,2.0,1.0,-1.0,0.0,3.0,3.0,-1.0}, {-1.0,1.0,1.0,0.0,-1.0,-2.0,-3.0,-1.0,0.0}, {0.0,0.0,1.0,1.0,-1.0,-1.0,-2.0,-2.0,2.0}, {0.0,2.0,1.0,0.0,-1.0,-1.0,1.0,3.0,-2.0}, {2.0,1.0,3.0,3.0,3.0,1.0,0.0,1.0,-1.0} }; int i, j; int nc = 0; int ii, jj; int ix = (int)floor(x); float xx = x - (float)ix; int iy = (int)floor(y); float yy = y - (float)iy; int qx = (int)(xx*4.0); int qy = (int)(yy*4.0); int qq = 0; if (qx >= 1 && qx <= 2 && qy >= 1 && qy <= 2) qq = 0; else if (qx >= 0 && qx <= 2 && qy == 3) qq = 1; else if (qx == 3 && qy == 3) qq = 2; else if (qx == 3 && qy == 2) qq = 3; else if (qx == 3 && qy == 1) qq = 4; else if (qx == 3 && qy == 0) qq = 5; else if (qx >= 1 && qx <= 2 && qy == 0) qq = 6; else if (qx == 0 && qy >= 0 && qy <= 1) qq = 7; else if (qx == 0 && qy == 2) qq = 8; for (ii = 0; ii < 9; ii++) { dx[nc] = sx[qq][ii] / 4.0; dy[nc] = sy[qq][ii] / 4.0; cx[nc] = (float)ix + ddx[qq][ii] / 4.0 + dx[nc]; cy[nc] = (float)iy + ddy[qq][ii] / 4.0 + dy[nc]; nc++; } return nc; } static int paved(float x, float y, // pavement parameters int Nx, float cx[MAX_NEIGH_CELLS], float cy[MAX_NEIGH_CELLS], float dx[MAX_NEIGH_CELLS], float dy[MAX_NEIGH_CELLS]) { int i, j; int ix = (int)floor(x); float xx = x - (float)ix; int iy = (int)floor(y); float yy = y - (float)iy; int qx = (int)(xx*(int)(2 * Nx)); int qy = (int)(yy*(int)(2 * Nx)); int nc = 0; // horizontal if ((qx >= qy && qx <= qy + Nx - 1) || (qx >= qy - 2 * Nx && qx <= qy + Nx - 1 - 2 * Nx)) { int rx, ry; if (qx >= qy && qx <= qy + Nx - 1) { rx = qy; ry = qy; } else { rx = qy - 2 * Nx; ry = qy; } for (i = 0; i < 3; i++) { cx[nc] = (float)ix + ((float)rx + (float)(i - 1) + (float)(Nx) *0.5) / (float)(2 * Nx); cy[nc] = (float)iy + ((float)ry + (float)(i - 1) + 0.5) / (float)(2 * Nx); dx[nc] = ((float)Nx*0.5) / (float)(2 * Nx); dy[nc] = 0.5 / (float)(2 * Nx); cx[nc + 1] = (float)ix + ((float)rx + (float)(i - 2) + 0.5) / (float)(2 * Nx); cy[nc + 1] = (float)iy + ((float)ry + (float)(i - 1) + (float)(Nx) *0.5) / (float)(2 * Nx); dx[nc + 1] = 0.5 / (float)(2 * Nx); dy[nc + 1] = ((float)Nx*0.5) / (float)(2 * Nx); cx[nc + 2] = (float)ix + ((float)rx + (float)(i - 1) + (float)Nx + 0.5) / (float)(2 * Nx); cy[nc + 2] = (float)iy + ((float)ry + (float)(i)-(float)(Nx)*0.5) / (float)(2 * Nx); dx[nc + 2] = 0.5 / (float)(2 * Nx); dy[nc + 2] = ((float)Nx*0.5) / (float)(2 * Nx); nc += 3; } } // vertical else { int rx, ry; if (qy >= qx + 1 && qy <= qx + 1 + Nx - 1) { rx = qx; ry = qx + 1; } else { rx = qx; ry = qx + 1 - 2 * Nx; } for (i = 0; i < 3; i++) { cx[nc] = (float)ix + ((float)rx + (float)(i - 1) + 0.5) / (float)(2 * Nx); cy[nc] = (float)iy + ((float)ry + (float)(i - 1) + (float)(Nx) *0.5) / (float)(2 * Nx); dx[nc] = 0.5 / (float)(2 * Nx); dy[nc] = ((float)Nx*0.5) / (float)(2 * Nx); cx[nc + 1] = (float)ix + ((float)rx + (float)(i - 1) + (float)(Nx)*0.5) / (float)(2 * Nx); cy[nc + 1] = (float)iy + ((float)ry + (float)(i - 2) + 0.5) / (float)(2 * Nx); dx[nc + 1] = ((float)Nx*0.5) / (float)(2 * Nx); dy[nc + 1] = 0.5 / (float)(2 * Nx); cx[nc + 2] = (float)ix + ((float)rx + (float)(i - 1) - (float)(Nx)*0.5) / (float)(2 * Nx); cy[nc + 2] = (float)iy + ((float)ry + (float)(i - 1) + (float)(Nx - 1) + 0.5) / (float)(2 * Nx); dx[nc + 2] = ((float)Nx*0.5) / (float)(2 * Nx); dy[nc + 2] = 0.5 / (float)(2 * Nx); nc += 3; } } return nc; } static int pavement(float x, float y, tilingtype tt, int decalx, int Nx, float ccx[MAX_NEIGH_CELLS], float ccy[MAX_NEIGH_CELLS], float cdx[MAX_NEIGH_CELLS], float cdy[MAX_NEIGH_CELLS]) { switch (tt) { case REGULAR: return hvNoise::pave(x, y, decalx, 0.0, 0.0, ccx, ccy, cdx, cdy); break; case IRREGULAR: return hvNoise::pave(x, y, decalx, 0.8, 0.8, ccx, ccy, cdx, cdy); break; case CROSS: return hvNoise::paved(x, y, Nx, ccx, ccy, cdx, cdy); break; case BISQUARE: return hvNoise::paveb(x, y, ccx, ccy, cdx, cdy); break; case IRREGULARX: return hvNoise::pave(x, y, decalx, 0.8, 0.0, ccx, ccy, cdx, cdy); break; case IRREGULARY: return hvNoise::pave(x, y, decalx, 0.0, 0.8, ccx, ccy, cdx, cdy); break; case APAVEMENT: return hvNoise::pavec(x, y, ccx, ccy, cdx, cdy); break; default: return hvNoise::pave(x, y, decalx, 0.0, 0.0, ccx, ccy, cdx, cdy); break; } } static int pointset( // point set parameters float psubx, float psuby, float jitx, float jity, int nn, float ccx[MAX_NEIGH_CELLS], float ccy[MAX_NEIGH_CELLS], float cdx[MAX_NEIGH_CELLS], float cdy[MAX_NEIGH_CELLS], float cx[MAX_NEIGH_CELLS * 4], float cy[MAX_NEIGH_CELLS * 4], float ncx[MAX_NEIGH_CELLS * 4], float ncy[MAX_NEIGH_CELLS * 4], float ndx[MAX_NEIGH_CELLS * 4], float ndy[MAX_NEIGH_CELLS * 4]) { unsigned int seed; int i, j, k; int nc = 0; for (k = 0; k < nn; k++) { int ix = (int)floor(ccx[k]); float xx = ccx[k] - (float)ix; int iy = (int)floor(ccy[k]); float yy = ccy[k] - (float)iy; seeding((unsigned int)((int)floor(ccx[k] * 15.0) + 10), (unsigned int)((int)floor(ccy[k] * 10.0) + 3), 0, seed); float subx = next(seed)*0.5 + 0.5; //float suby = next()*0.5 + 0.5; float dif = cdx[k] - cdy[k]; if (dif < 0.0) dif = -dif; //printf("dif=%g, psubx=%g(%g), psuby=%g(%g)\n", dif,psubx,subx,psuby,suby); if (dif < 0.1 && (subx < psubx)) // || suby<psuby)) { float cutx = 0.5 + 0.2*next(seed)*jitx; float cuty = 0.5 + 0.2*next(seed)*jity; float ncdx, ncdy, nccx, nccy, rx, ry; ncdx = (cutx*2.0*cdx[k])*0.5; ncdy = (cuty*2.0*cdy[k])*0.5; nccx = ccx[k] - cdx[k] + ncdx; nccy = ccy[k] - cdy[k] + ncdy; rx = ncdx * next(seed)*jitx; ry = ncdy * next(seed)*jity; cx[nc] = nccx + rx; cy[nc] = nccy + ry; ncx[nc] = nccx; ncy[nc] = nccy; ndx[nc] = ncdx; ndy[nc] = ncdy; nc++; ncdx = ((1.0 - cutx)*2.0*cdx[k])*0.5; ncdy = (cuty*2.0*cdy[k])*0.5; nccx = ccx[k] - cdx[k] + (cutx*2.0*cdx[k]) + ncdx; nccy = ccy[k] - cdy[k] + ncdy; rx = ncdx * next(seed)*jitx; ry = ncdy * next(seed)*jity; cx[nc] = nccx + rx; cy[nc] = nccy + ry; ncx[nc] = nccx; ncy[nc] = nccy; ndx[nc] = ncdx; ndy[nc] = ncdy; nc++; ncdx = (cutx*2.0*cdx[k])*0.5; ncdy = ((1.0 - cuty)*2.0*cdy[k])*0.5; nccx = ccx[k] - cdx[k] + ncdx; nccy = ccy[k] - cdy[k] + (cuty*2.0*cdy[k]) + ncdy; rx = ncdx * next(seed)*jitx; ry = ncdy * next(seed)*jity; cx[nc] = nccx + rx; cy[nc] = nccy + ry; ncx[nc] = nccx; ncy[nc] = nccy; ndx[nc] = ncdx; ndy[nc] = ncdy; nc++; ncdx = ((1.0 - cutx)*2.0*cdx[k])*0.5; ncdy = ((1.0 - cuty)*2.0*cdy[k])*0.5; nccx = ccx[k] - cdx[k] + (cutx*2.0*cdx[k]) + ncdx; nccy = ccy[k] - cdy[k] + (cuty*2.0*cdy[k]) + ncdy; rx = ncdx * next(seed)*jitx; ry = ncdy * next(seed)*jity; cx[nc] = nccx + rx; cy[nc] = nccy + ry; ncx[nc] = nccx; ncy[nc] = nccy; ndx[nc] = ncdx; ndy[nc] = ncdy; nc++; } else if (cdx[k] > cdy[k] + 0.1 && subx < psubx) { float cutx = 0.4 + 0.2*(next(seed)*0.5 + 0.5); float cuty = 1.0; float ncdx, ncdy, nccx, nccy, rx, ry; ncdx = (cutx*2.0*cdx[k])*0.5; ncdy = (cuty*2.0*cdy[k])*0.5; nccx = ccx[k] - cdx[k] + ncdx; nccy = ccy[k] - cdy[k] + ncdy; rx = ncdx * next(seed)*jitx; ry = ncdy * next(seed)*jity; cx[nc] = nccx + rx; cy[nc] = nccy + ry; ncx[nc] = nccx; ncy[nc] = nccy; ndx[nc] = ncdx; ndy[nc] = ncdy; nc++; ncdx = ((1.0 - cutx)*2.0*cdx[k])*0.5; ncdy = (cuty*2.0*cdy[k])*0.5; nccx = ccx[k] - cdx[k] + (cutx*2.0*cdx[k]) + ncdx; nccy = ccy[k] - cdy[k] + ncdy; rx = ncdx * next(seed)*jitx; ry = ncdy * next(seed)*jity; cx[nc] = nccx + rx; cy[nc] = nccy + ry; ncx[nc] = nccx; ncy[nc] = nccy; ndx[nc] = ncdx; ndy[nc] = ncdy; nc++; } else if (cdy[k] > cdx[k] + 0.1 && subx < psuby) { float cutx = 1.0; float cuty = 0.4 + 0.2*(next(seed)*0.5 + 0.5); float ncdx, ncdy, nccx, nccy, rx, ry; ncdx = (cutx*2.0*cdx[k])*0.5; ncdy = (cuty*2.0*cdy[k])*0.5; nccx = ccx[k] - cdx[k] + ncdx; nccy = ccy[k] - cdy[k] + ncdy; rx = ncdx * next(seed)*jitx; ry = ncdy * next(seed)*jity; cx[nc] = nccx + rx; cy[nc] = nccy + ry; ncx[nc] = nccx; ncy[nc] = nccy; ndx[nc] = ncdx; ndy[nc] = ncdy; nc++; ncdx = (cutx*2.0*cdx[k])*0.5; ncdy = ((1.0 - cuty)*2.0*cdy[k])*0.5; nccx = ccx[k] - cdx[k] + ncdx; nccy = ccy[k] - cdy[k] + (cuty*2.0*cdy[k]) + ncdy; rx = ncdx * next(seed)*jitx; ry = ncdy * next(seed)*jity; cx[nc] = nccx + rx; cy[nc] = nccy + ry; ncx[nc] = nccx; ncy[nc] = nccy; ndx[nc] = ncdx; ndy[nc] = ncdy; nc++; } else { float rx = cdx[k] * next(seed)*jitx; float ry = cdy[k] * next(seed)*jity; cx[nc] = ccx[k] + rx; cy[nc] = ccy[k] + ry; ncx[nc] = ccx[k]; ncy[nc] = ccy[k]; ndx[nc] = cdx[k]; ndy[nc] = cdy[k]; nc++; } } return nc; } static void relax(int nrelax, int n, float bx, float by, float dx, float dy, float cx[MAX_NEIGH_CELLS * 4], float cy[MAX_NEIGH_CELLS * 4], float bcx[MAX_NEIGH_CELLS * 4], float bcy[MAX_NEIGH_CELLS * 4], float dcx[MAX_NEIGH_CELLS * 4], float dcy[MAX_NEIGH_CELLS * 4]) { int i, j, k; float mcx[MAX_NEIGH_CELLS * 4], mcy[MAX_NEIGH_CELLS * 4]; for (i = 0; i < nrelax; i++) { for (k = 0; k < n; k++) if (cx[k] >= bx - dx && cx[k] <= bx + dx && cy[k] >= by - dy && cy[k] <= by + dy) { float distmin1 = 100000.0; int ind1 = 0; float distmin2 = 100000.0; int ind2 = 0; float distmin3 = 100000.0; int ind3 = 0; for (j = 0; j < n; j++) if (j != k) { float dd = sqrt((cx[k] - cx[j])*(cx[k] - cx[j]) + (cy[k] - cy[j])*(cy[k] - cy[j])); if (dd < distmin1) { distmin3 = distmin2; ind3 = ind2; distmin2 = distmin1; ind2 = ind1; distmin1 = dd; ind1 = j; } else if (dd < distmin2) { distmin3 = distmin2; ind3 = ind2; distmin2 = dd; ind2 = j; } else if (dd < distmin3) { distmin3 = dd; ind3 = j; } } float dx1 = cx[ind1] - cx[k]; float dy1 = cy[ind1] - cy[k]; float no1 = sqrt((double)(dx1*dx1 + dy1 * dy1)); if (no1 == 0.0) no1 = 1.0; float dx2 = cx[ind2] - cx[k]; float dy2 = cy[ind2] - cy[k]; float no2 = sqrt((double)(dx2*dx2 + dy2 * dy2)); if (no2 == 0.0) no2 = 1.0; float dx3 = cx[ind3] - cx[k]; float dy3 = cy[ind3] - cy[k]; float no3 = sqrt((double)(dx3*dx3 + dy3 * dy3)); if (no3 == 0.0) no3 = 1.0; float dirx = dx1 / no1 / no1 + dx2 / no2 / no2 + dx3 / no3 / no3; float diry = dy1 / no1 / no1 + dy2 / no2 / no2 + dy3 / no3 / no3; float no = sqrt(dirx*dirx + diry * diry); if (no == 0.0) no = 1.0; mcx[k] = cx[k] - (dirx / no * 0.05); mcy[k] = cy[k] - (diry / no * 0.05); if (mcx[k] < bcx[k] - dcx[k] + 0.05) mcx[k] = bcx[k] - dcx[k] + 0.05; if (mcx[k] > bcx[k] + dcx[k] - 0.05) mcx[k] = bcx[k] + dcx[k] - 0.05; if (mcy[k] < bcy[k] - dcy[k] + 0.05) mcy[k] = bcy[k] - dcy[k] + 0.05; if (mcy[k] > by + dy) mcy[k] = bcy[k] + dcy[k] - 0.05; } else { mcx[k] = cx[k]; mcy[k] = cy[k]; } for (k = 0; k < n; k++) { cx[k] = mcx[k]; cy[k] = mcy[k]; } } } static int distribute(float px, float py, // point set parameters tilingtype tt, float psubx, float psuby, int decalx, int Nx, int nrelax, float jitter, float cx[MAX_NEIGH_CELLS * 4], float cy[MAX_NEIGH_CELLS * 4], float ncx[MAX_NEIGH_CELLS * 4], float ncy[MAX_NEIGH_CELLS * 4], float ndx[MAX_NEIGH_CELLS * 4], float ndy[MAX_NEIGH_CELLS * 4]) { int i, k; float ccx[MAX_NEIGH_CELLS]; float ccy[MAX_NEIGH_CELLS]; float cdx[MAX_NEIGH_CELLS]; float cdy[MAX_NEIGH_CELLS]; int nn = hvNoise::pavement(px, py, tt, decalx, Nx, ccx, ccy, cdx, cdy); int np = 0; if (nrelax == 0) np = hvNoise::pointset(psubx, psuby, 0.9, 0.9, nn, ccx, ccy, cdx, cdy, cx, cy, ncx, ncy, ndx, ndy); else for (k = 0; k < nn; k++) { float gccx[MAX_NEIGH_CELLS]; float gccy[MAX_NEIGH_CELLS]; float gcdx[MAX_NEIGH_CELLS]; float gcdy[MAX_NEIGH_CELLS]; float gcx[MAX_NEIGH_CELLS * 4]; float gcy[MAX_NEIGH_CELLS * 4]; float gncx[MAX_NEIGH_CELLS * 4]; float gncy[MAX_NEIGH_CELLS * 4]; float gndx[MAX_NEIGH_CELLS * 4]; float gndy[MAX_NEIGH_CELLS * 4]; int nsub = hvNoise::pavement(ccx[k], ccy[k], tt, decalx, Nx, gccx, gccy, gcdx, gcdy); int npk = hvNoise::pointset(psubx, psuby, 0.9, 0.9, nsub, gccx, gccy, gcdx, gcdy, gcx, gcy, gncx, gncy, gndx, gndy); hvNoise::relax(nrelax, npk, ccx[k], ccy[k], cdx[k], cdy[k], gcx, gcy, gncx, gncy, gndx, gndy); for (i = 0; i < npk; i++) if (gcx[i] >= ccx[k] - cdx[k] && gcx[i] <= ccx[k] + cdx[k] && gcy[i] >= ccy[k] - cdy[k] && gcy[i] <= ccy[k] + cdy[k]) { cx[np] = gcx[i]; cy[np] = gcy[i]; ncx[np] = gncx[i]; ncy[np] = gncy[i]; ndx[np] = gndx[i]; ndy[np] = gndy[i]; np++; } } for (i = 0; i < np; i++) { cx[i] = cx[i] * jitter + ncx[i] * (1.0 - jitter); cy[i] = cy[i] * jitter + ncy[i] * (1.0 - jitter); } return np; } static int genPointSet(float x, float y, // point set parameters int pointsettype, float jitter, float px[MAX_NEIGH_CELLS * 4], float py[MAX_NEIGH_CELLS * 4], float ncx[MAX_NEIGH_CELLS * 4], float ncy[MAX_NEIGH_CELLS * 4], float ndx[MAX_NEIGH_CELLS * 4], float ndy[MAX_NEIGH_CELLS * 4]) { tilingtype tt; float ppointsub; int decalx; int Nx; int nrelax; //printf("pointsett=%d\n", pointsettype); switch (pointsettype) { case 0: tt = hvNoise::REGULAR; ppointsub = 0.0; decalx = 1; Nx = 0; nrelax = 0; break; case 1: tt = hvNoise::REGULAR; ppointsub = 0.5; decalx = 1; Nx = 0; nrelax = 0; break; case 2: tt = hvNoise::REGULAR; ppointsub = 1.0; decalx = 1; Nx = 0; nrelax = 5; break; case 3: tt = hvNoise::REGULAR; ppointsub = 0.5; decalx = 1; Nx = 0; nrelax = 5; break; case 4: tt = hvNoise::REGULAR; ppointsub = 0.0; decalx = 2; Nx = 0; nrelax = 0; break; case 5: tt = hvNoise::REGULAR; ppointsub = 0.0; decalx = 3; Nx = 0; nrelax = 0; break; case 6: tt = hvNoise::IRREGULAR; ppointsub = 0.0; decalx = 1; Nx = 0; nrelax = 0; break; case 7: tt = hvNoise::IRREGULAR; ppointsub = 0.5; decalx = 1; Nx = 0; nrelax = 0; break; case 8: tt = hvNoise::IRREGULARX; ppointsub = 0.0; decalx = 1; Nx = 0; nrelax = 0; break; case 9: tt = hvNoise::IRREGULARX; ppointsub = 0.5; decalx = 1; Nx = 0; nrelax = 0; break; case 10: tt = hvNoise::CROSS; ppointsub = 0.0; decalx = 0; Nx = 2; nrelax = 0; break; case 11: tt = hvNoise::CROSS; ppointsub = 0.5; decalx = 0; Nx = 2; nrelax = 0; break; case 12: tt = hvNoise::CROSS; ppointsub = 0.0; decalx = 0; Nx = 3; nrelax = 0; break; case 13: tt = hvNoise::CROSS; ppointsub = 0.5; decalx = 0; Nx = 3; nrelax = 0; break; case 14: tt = hvNoise::BISQUARE; ppointsub = 0.0; decalx = 0; Nx = 1; nrelax = 0; break; case 15: tt = hvNoise::BISQUARE; ppointsub = 0.5; decalx = 0; Nx = 1; nrelax = 0; break; case 16: tt = hvNoise::APAVEMENT; ppointsub = 0.0; decalx = 0; Nx = 1; nrelax = 0; break; case 17: tt = hvNoise::APAVEMENT; ppointsub = 0.5; decalx = 0; Nx = 1; nrelax = 0; break; default: tt = hvNoise::REGULAR; ppointsub = 0.0; decalx = 1; Nx = 0; nrelax = 0; break; } // compute points return hvNoise::distribute(x, y, tt, ppointsub, ppointsub, decalx, Nx, nrelax, jitter, px, py, ncx, ncy, ndx, ndy); } static float cdistance(float x1, float y1, float x2, float y2, float norm, float cx, float cy, float dx, float dy, float larp) { //seeding((unsigned int)(cx*12.0 + 5.0), (unsigned int)(cy*12.0 + 11.0), 0); //float ss = size*next(); float ddx = (x1 - x2); float ddy = (y1 - y2); float ex = ddx < 0.0 ? -ddx / (x2 - cx + dx) : ddx / (cx + dx - x2); float ey = ddy < 0.0 ? -ddy / (y2 - cy + dy) : ddy / (cy + dy - y2); //float lx = (1.0 - larp)*abs(ddx) + larp*ex; //float ly = (1.0 - larp)*abs(ddy) + larp*ey; //float no = (float)pow(pow(lx, norm) + pow(ly, norm), 1.0 / norm); //if (norm <= 2.0) return(no); //else return (norm - 2.0)*(lx > ly ? lx : ly) + (1.0 - (norm - 2.0))*no; //printf("cdist: ddx=%g,ddy=%g, ex=%g, ey=%g, dx=%g,dy=%g\n", ddx, ddy, ex, ey, dx, dy); //return (larp*(float)pow(pow(abs(ddx), norm) + pow(abs(ddy), norm), 1.0 / norm) //+(1.0-larp)*(ex > ey ? ex : ey)); return ((1.0 - larp)*pow(pow(abs(ddx), norm) + pow(abs(ddy), norm), 1.0 / norm) + larp * (ex > ey ? ex : ey)); } static int cclosest(float xx, float yy, float cx[], float cy[], int nc, float norm, float cnx[], float cny[], float dx[], float dy[], float larp) { int mink = 0; float mind = 0.0; int k; for (k = 0; k < nc; k++) { float dd = cdistance(xx, yy, cx[k], cy[k], norm, cnx[k], cny[k], dx[k], dy[k], larp); //float dx = xx - cx[k]; //float dy = yy - cy[k]; //float dd = (float)pow(pow(abs(dx), norm) + pow(abs(dy), norm), 1.0 / norm); if (k == 0) { mind = dd; } else if (mind > dd) { mink = k; mind = dd; } } return mink; } static void nthclosest(int mink[], int nn, float xx, float yy, float cx[], float cy[], int nc, float norm, float ncx[], float ncy[], float dx[], float dy[], float larp) { int i, k; float dist[200]; for (k = 0; k < nc; k++) { float dd = cdistance(xx, yy, cx[k], cy[k], norm, ncx[k], ncy[k], dx[k], dy[k], larp); //float dx = xx - cx[k]; //float dy = yy - cy[k]; //float dd = (float)pow(pow(abs(dx), norm) + pow(abs(dy), norm), 1.0 / norm); dist[k] = dd; } for (i = 0; i < nn; i++) { int mk = 0; for (k = 1; k < nc; k++) { if (dist[mk] > dist[k]) mk = k; } mink[i] = mk; dist[mk] = 100000.0; } } static float celldist(float ixx, float iyy, int k, int mink, float cx[], float cy[], int nc, float norm, float cnx[], float cny[], float dx[], float dy[], float larp) { float delta = 0.2; int count, nk; float xx, yy, ddx, ddy, dd; do { xx = ixx; yy = iyy; ddx = cx[k] - xx; ddy = cy[k] - yy; dd = (float)sqrt(ddx*ddx + ddy * ddy); if (dd < 0.001) return 0.0; ddx *= delta / dd; ddy *= delta / dd; if (k == mink) { ddx = -ddx; ddy = -ddy; } //printf("start with cell %d, %d, %g,%g, %g,%g, %g,%g ->%g,%g\n", k, mink, ddx, ddy, ixx, iyy, cx[k], cy[k], xx, yy); //printf("cell is: %g,%g, (%g,%g)\n", cnx[k], cny[k], dx[k], dy[k]); //printf("mincell is: %g,%g, (%g,%g)\n", cnx[mink], cny[mink], dx[mink], dy[mink]); count = 0; //nk = cclosest(xx+ddx, yy+ddy, cx, cy, nc, norm, cnx, cny, dx, dy, larp); //if (!((k == mink && nk == k) || (k != mink&&nk != k))) { // printf("start problem with cell, %d, %d, %g,%g, %g,%g, %g,%g ->%g,%g\n", k, mink, dx, dy, ixx, iyy, cx[k], cy[k], xx, yy); //} do { xx += ddx; yy += ddy; nk = cclosest(xx, yy, cx, cy, nc, norm, cnx, cny, dx, dy, larp); //if (count>97) printf("%d, nk=%d, xx=%g,yy=%g, delta=%g\n", count, nk, xx, yy, delta); count++; } while (((k == mink && nk == k) || (k != mink && nk != k)) && count < 100); if (count == 100 && delta <= 0.009) { printf("problem with cell, %d, %d, displ:%g,%g, \nfrom: %g,%g, cell:%g,%g ->at: %g,%g\n", k, mink, ddx, ddy, ixx, iyy, cx[k], cy[k], xx, yy); printf("in cell: %g,%g, (%g,%g)\n", cnx[k], cny[k], dx[k], dy[k]); for (int u = 0; u < nc; u++) if (u != k) printf("neighbor cell %d: %g,%g, (%g,%g)\n", u, cnx[u], cny[u], dx[u], dy[u]); hvFatal("error"); } delta /= 2.0f; } while (count == 100 && delta >= 0.01); float xa = xx - ddx, ya = yy - ddy; float midx = (xa + xx) / 2.0, midy = (ya + yy) / 2.0; //printf("refine ddx=%g, ddy=%g, midx=%g,midy=%g, cx=%g,cy=%g,cnx=%g,cny=%g,dx=%g,dy=%g\n", ddx, ddy, midx, midy, cx[k], cy[k], cnx[k], cny[k], dx[k], dy[k]); for (int i = 0; i < 5; i++) { nk = cclosest(midx, midy, cx, cy, nc, norm, cnx, cny, dx, dy, larp); if (((k == mink && nk == k) || (k != mink && nk != k))) { xa = midx; ya = midy; } else { xx = midx; yy = midy; } midx = (xa + xx) / 2.0; midy = (ya + yy) / 2.0; } //float cdi=cdistance(midx, midy, cx[k], cy[k], norm, cnx[k], cny[k], dx[k], dy[k], larp); //printf("%g : k=%d, mink=%d, ddx=%g, ddy=%g, midx=%g,midy=%g, cx=%g,cy=%g,cnx=%g,cny=%g,dx=%g,dy=%g\n", cdi, k, mink, ddx, ddy, midx, midy, cx[k], cy[k], cnx[k], cny[k], dx[k], dy[k]); //return cdi; float vdx = cx[k] - midx, vdy = cy[k] - midy; //return (float)pow(pow(abs(dx), norm) + pow(abs(dy), norm), 1.0 / norm); return sqrt(vdx*vdx + vdy * vdy); } static float interTriangle(float origx, float origy, float ddx, float ddy, float startx, float starty, float endx, float endy) { float dirx = (endx - startx); float diry = (endy - starty); float dirno = sqrt(dirx*dirx + diry * diry); dirx /= dirno; diry /= dirno; float val = ddx * diry - ddy * dirx; float segx = -(startx - origx); float segy = -(starty - origy); float lambda = (dirx*segy - diry * segx) / val; return lambda; } static void bezier2(float ts, float p0x, float p0y, float p1x, float p1y, float p2x, float p2y, float &splinex, float &spliney) { float p01x = ts * p1x + (1.0 - ts)*p0x; float p01y = ts * p1y + (1.0 - ts)*p0y; float p11x = ts * p2x + (1.0 - ts)*p1x; float p11y = ts * p2y + (1.0 - ts)*p1y; splinex = ts * p11x + (1.0 - ts)*p01x; spliney = ts * p11y + (1.0 - ts)*p01y; } ///////////////////////////////////////////////////// POINT PROCESS NOISE with cell center static float cpptbf_gen_v2c(float xx, float yy, // deformation and normalization float zoom, float alpha, float rescalex, float ampli[3], // point set parameters int tt, float jitter, // window function parameters int winshape, float arity, // voroi cell polygon arity float larp, // anisotropy of cell norm float wsmooth, float norm, float normblend, float normsig, // feature function parameters int bomb, float normfeat, float winfeatcorrel, float feataniso, int Npmin, int Npmax, float sigcos, float sigcosvar, float freq, float phase, float thickness, float courbure, float deltaorient, float &pointvalue, float &cellpointx, float &cellpointy ) { unsigned int seed; int i, k; float cx[MAX_NEIGH_CELLS]; float cy[MAX_NEIGH_CELLS]; float dx[MAX_NEIGH_CELLS]; float dy[MAX_NEIGH_CELLS]; float px[MAX_NEIGH_CELLS * 4], py[MAX_NEIGH_CELLS * 4], ncx[MAX_NEIGH_CELLS * 4], ncy[MAX_NEIGH_CELLS * 4], ndx[MAX_NEIGH_CELLS * 4], ndy[MAX_NEIGH_CELLS * 4]; //---------------- // [1] Deformation //---------------- // Apply turbulence (i.e. noise-based spatial distorsion) float distortamp = ampli[0]; float distortfact = ampli[1]; // \in ]0,1] float distortfreq = ampli[2]; // \in [0,1] // - x position float ppx = xx + distortamp * cnoise2D(distortfreq*xx*zoom*0.5 + 2.0, distortfreq*yy*zoom*0.5) + distortamp * distortfact * cnoise2D(distortfreq*xx*zoom + 2.0, distortfreq*yy*zoom) + distortamp * distortfact * distortfact * cnoise2D(distortfreq*xx*zoom*2.0 + 2.0, distortfreq*yy*zoom*2.0) + distortamp * distortfact * distortfact * distortfact * cnoise2D(distortfreq*xx*zoom*4.0 + 2.0, distortfreq*yy*zoom*4.0); // - y position float ppy = yy + distortamp * cnoise2D(distortfreq*xx*zoom*0.5, distortfreq*yy*zoom*0.5 + 5.0) + distortamp * distortfact * cnoise2D(distortfreq*xx*zoom, distortfreq*yy*zoom + 5.0) + distortamp * distortfact * distortfact * cnoise2D(distortfreq*xx*zoom*2.0, distortfreq*yy*zoom*2.0 + 5.0) + distortamp * distortfact * distortfact * distortfact * cnoise2D(distortfreq*xx*zoom*4.0, distortfreq*yy*zoom*4.0 + 5.0); //-------------------- // [2] Model Transform //-------------------- // Apply other transforms: rescale, rotation and zoom // Apply also a shift +100.0 to avoid negative coordinates float x = 100.0 + (ppx * cos(-alpha) + ppy * sin(-alpha)) / rescalex * zoom; float y = 100.0 + (-ppx * sin(-alpha) + ppy * cos(-alpha)) * zoom; //------------------ // [3] Point Process //------------------ // compute points int nc = hvNoise::genPointSet(x, y, tt, jitter, px, py, ncx, ncy, ndx, ndy); int mink[MAX_NEIGH_CELLS * 4]; int npp = (nc < 18 ? nc : 18); hvNoise::nthclosest(mink, npp, x, y, px, py, nc, norm, ncx, ncy, ndx, ndy, larp); //------------------------- // [4] PPTBF = PP x ( W F ) //------------------------- float vv = 0.0f; // final value, to be computed and returned float winsum = 0.0f; // for normalization float pmax = -1.0f; // initial lowest priority for bombing float closestdist = -100.0f; // initial value for min distance for (k = 0; k < npp; k++) // for each neighbor cell / point { // generate all random values of the cell / point seeding((unsigned int)(px[mink[k]] * 12.0 + 7.0), (unsigned int)(py[mink[k]] * 12.0 + 1.0), 0, seed ); float dalpha = 2.0 * M_PI / pow(2.0, (float)((unsigned int)(arity + 0.5))); float rotalpha = dalpha * (next(seed) * 0.5 + 0.5); float npointvalue = next(seed); if (k == 0) { pointvalue = npointvalue; cellpointx = px[mink[k]]; cellpointy = py[mink[k]]; } //float npointvalue = mval + vval*next(); //if (k == 0) pointvalue = npointvalue; int nn = Npmin + (int)((float)(Npmax - Npmin)*(0.5*next(seed) + 0.5)); if (nn > 20) { printf("Npmin=%d, Npmax=%d\n", Npmin, Npmax); hvFatal("stop"); } //printf("k=%d,mink=%d, px,py=%g,%g, nn=%d\n", k, mink[k], px[mink[k]], py[mink[k]], nn); //----------------------- // [5] Window Function: W //----------------------- // compute Window function: it is a blend between cellular and classical window functions //////////////////////////////////////////////////////////////////////// float ddx = (x - px[mink[k]]); // / ndx[mink[k]]; float ddy = (y - py[mink[k]]); // / ndy[mink[k]]; float sdd = sqrt(ddx * ddx + ddy * ddy); float sddno = pow(pow(abs(ddx), norm) + pow(abs(ddy), norm), 1.0 / norm); if (norm > 2.0) sddno = (norm - 2.0) * (abs(ddx) > abs(ddy) ? abs(ddx) : abs(ddy)) + (1.0 - (norm - 2.0)) * sddno; float gauss = 1.0; float foot[4] = { 1.2, 1.0, 1.0, 1.0 }; float footprint = foot[winshape]; // * ( 1.0 + 0.2 * jitter * next() ); if (tt >= 10) footprint *= 0.4; switch (winshape) { //case 0: if (sddno < 1.0 * footprint / 4.0) gauss = 1.0; // tapered cosine window // else if (sddno < footprint) gauss = 0.5 * (1.0 + cos(M_PI * 4.0 / footprint / 3.0 * (sddno - footprint / 4.0))); // else gauss = 0.0; // break; case 0: case 1: gauss = (exp(-2.0 * sddno) - exp(-2.0 * footprint)) / (1.0 - exp(-2.0 * footprint)); break; // clamped gaussian case 2: gauss = 1.0 - sddno / footprint; break; // triangular window case 3: if (sddno > footprint) gauss = 0.0; break; // rectangular window default: gauss = 1.0 - sddno / footprint; break; // triangular window } if (gauss < 0.0) gauss = 0.0; else if (gauss > 1.0) gauss = 1.0; //-------------------- // [6] Cellular Window //-------------------- // compute cellular value float cv = 0.0; if (k == 0) // if inside closest cell then compute cellular value, outside it is 0 { ////////////////////////////////////////////////////////// // compute position inside cell in polar coordinates ddx /= sdd; ddy /= sdd; float dd = sdd; float alpha = acos(ddx); if (ddy < 0.0) alpha = 2.0*M_PI - alpha; float palpha = alpha - rotalpha; if (palpha < 0.0) palpha += 2.0*M_PI; int ka = (int)(palpha / dalpha); float rka = palpha / dalpha - (float)ka; float ptx = px[mink[0]] + 0.1*cos(dalpha*(float)ka + rotalpha); float pty = py[mink[0]] + 0.1*sin(dalpha*(float)ka + rotalpha); float celldd1 = hvNoise::celldist(ptx, pty, mink[k], mink[0], px, py, nc, 2.0, ncx, ncy, ndx, ndy, larp); float startx = px[mink[0]] + celldd1*cos(dalpha*(float)ka + rotalpha); float starty = py[mink[0]] + celldd1*sin(dalpha*(float)ka + rotalpha); ptx = px[mink[0]] + 0.1*cos(dalpha*(float)ka + dalpha + rotalpha); pty = py[mink[0]] + 0.1*sin(dalpha*(float)ka + dalpha + rotalpha); float celldd2 = hvNoise::celldist(ptx, pty, mink[k], mink[0], px, py, nc, 2.0, ncx, ncy, ndx, ndy, larp); float endx = px[mink[0]] + celldd2*cos(dalpha*(float)ka + dalpha + rotalpha); float endy = py[mink[0]] + celldd2*sin(dalpha*(float)ka + dalpha + rotalpha); // for smoothing the cell using Bezier float midx = (startx + endx) / 2.0; float midy = (starty + endy) / 2.0; float middx = (midx - px[mink[0]]); float middy = (midy - py[mink[0]]); float midno = sqrt(middx*middx + middy*middy); middx /= midno; middy /= midno; //printf("acos=%g, dalpha=%g\n", acos(middx*ddx + middy*ddy) / M_PI, dalpha/M_PI); float midalpha = acos(middx); if (middy < 0.0) midalpha = 2.0*M_PI - midalpha; float diff = alpha - midalpha; if (diff < 0.0) diff = -diff; if (diff > 2.0*dalpha && alpha < 2.0*dalpha) midalpha -= 2.0*M_PI; else if (diff > 2.0*dalpha && alpha > 2.0*M_PI - 2.0*dalpha) midalpha += 2.0*M_PI; float splinex, spliney; float smoothx, smoothy; if (alpha > midalpha) { ptx = px[mink[0]] + 0.1*cos(dalpha*(float)ka + 2.0*dalpha + rotalpha); pty = py[mink[0]] + 0.1*sin(dalpha*(float)ka + 2.0*dalpha + rotalpha); float celldd = hvNoise::celldist(ptx, pty, mink[k], mink[0], px, py, nc, 2.0, ncx, ncy, ndx, ndy, larp); float nendx = px[mink[0]] + celldd*cos(dalpha*(float)ka + 2.0*dalpha + rotalpha); float nendy = py[mink[0]] + celldd*sin(dalpha*(float)ka + 2.0*dalpha + rotalpha); float vvx = (endx - startx), vvy = (endy - starty); float nn = sqrt(vvx*vvx + vvy*vvy); vvx /= nn; vvy /= nn; float wwx = (nendx - endx), wwy = (nendy - endy); nn = sqrt(wwx*wwx + wwy*wwy); wwx /= nn; wwy /= nn; nendx = (nendx + endx) / 2.0; nendy = (nendy + endy) / 2.0; float lambda = hvNoise::interTriangle(px[mink[0]], py[mink[0]], ddx, ddy, midx, midy, nendx, nendy); float bordx = ddx*lambda + px[mink[0]]; float bordy = ddy*lambda + py[mink[0]]; float dirno = sqrt((nendx - midx)*(nendx - midx) + (nendy - midy)*(nendy - midy)); float ts = sqrt((bordx - midx)*(bordx - midx) + (bordy - midy)*(bordy - midy)); ts /= dirno; hvNoise::bezier2(ts, midx, midy, endx, endy, nendx, nendy, splinex, spliney); smoothx = bordx; smoothy = bordy; } else { ptx = px[mink[0]] + 0.1*cos(dalpha*(float)ka - dalpha + rotalpha); pty = py[mink[0]] + 0.1*sin(dalpha*(float)ka - dalpha + rotalpha); float celldd = hvNoise::celldist(ptx, pty, mink[k], mink[0], px, py, nc, 2.0, ncx, ncy, ndx, ndy, larp); float nstartx = px[mink[0]] + celldd*cos(dalpha*(float)ka - dalpha + rotalpha); float nstarty = py[mink[0]] + celldd*sin(dalpha*(float)ka - dalpha + rotalpha); float vvx = (startx - nstartx), vvy = (starty - nstarty); float nn = sqrt(vvx*vvx + vvy*vvy); vvx /= nn; vvy /= nn; float wwx = (endx - startx), wwy = (endy - starty); nn = sqrt(wwx*wwx + wwy*wwy); wwx /= nn; wwy /= nn; nstartx = (nstartx + startx) / 2.0; nstarty = (nstarty + starty) / 2.0; float lambda = hvNoise::interTriangle(px[mink[0]], py[mink[0]], ddx, ddy, nstartx, nstarty, midx, midy); float bordx = ddx*lambda + px[mink[0]]; float bordy = ddy*lambda + py[mink[0]]; float dirno = sqrt((midx - nstartx)*(midx - nstartx) + (midy - nstarty)*(midy - nstarty)); float ts = sqrt((bordx - nstartx)*(bordx - nstartx) + (bordy - nstarty)*(bordy - nstarty)); ts /= dirno; hvNoise::bezier2(ts, nstartx, nstarty, startx, starty, midx, midy, splinex, spliney); smoothx = bordx; smoothy = bordy; } float lambda = hvNoise::interTriangle(px[mink[0]], py[mink[0]], ddx, ddy, startx, starty, endx, endy); float bordx = ddx*lambda + px[mink[0]]; float bordy = ddy*lambda + py[mink[0]]; float smoothdist = sqrt((smoothx - px[mink[0]])*(smoothx - px[mink[0]]) + (smoothy - py[mink[0]])*(smoothy - py[mink[0]])); float splinedist = sqrt((splinex - px[mink[0]])*(splinex - px[mink[0]]) + (spliney - py[mink[0]])*(spliney - py[mink[0]])); if (wsmooth < 1.0) cv = (1.0 - wsmooth)*(1.0 - dd / lambda) + wsmooth*(1.0 - dd / smoothdist); else if (wsmooth < 2.0) cv = (2.0 - wsmooth)*(1.0 - dd / smoothdist) + (wsmooth - 1.0)*(1.0 - dd / splinedist); else cv = 1.0 - dd / splinedist; if (cv < 0.0) cv = 0.0; else if (cv > 1.0) cv = 1.0; } // blend the cellular window with the classical window float coeff1 = normblend * (exp((cv - 1.0)*normsig) - exp(-1.0*normsig)) / (1.0 - exp(-1.0*normsig)); float coeff2 = (1.0 - normblend) * gauss; //winsum += coeff; winsum += coeff1 + coeff2; //if (k==0) printf("k=%d,cv=%g,gauss=%g,coeff=%g,winsum=%g\n", k, cv,gauss, coeff,winsum); //--------------------- // [7] Feature Function //--------------------- // Feature function, by default is constant=1.0 float feat = 0.0; float lx[20], ly[20], deltalx[20], deltaly[20], angle[20], prior[20], sigb[20], valb[20]; // , sigma[20]; seeding((unsigned int)(px[mink[k]] * 15.0 + 2.0), (unsigned int)(py[mink[k]] * 15.0 + 5.0), 0, seed); //valb[ 0 ] = next(); //prior[ 0 ] = next() * 0.5 + 0.5; //lx[ 0 ] = px[ mink[ k ] ]; //ly[ 0 ] = py[ mink[ k ] ]; //deltalx[ 0 ] = ( x - lx[ 0 ] ) / ndx[ mink[ k ] ]; //deltaly[ 0 ] = ( y - ly[ 0 ] ) / ndy[ mink[ k ] ]; //angle[ 0 ] = deltaorient * next(); //sigb[ 0 ] = sigcos * ( 1.0 + ( next() + 1.0 ) / 2.0 * sigcosvar ); for (int i = 0; i < nn; i++) { valb[i] = next(seed); prior[i] = next(seed) * 0.5 + 0.5; lx[i] = ncx[mink[k]] + next(seed) * 0.98 * ndx[mink[k]]; ly[i] = ncy[mink[k]] + next(seed) * 0.98 * ndy[mink[k]]; lx[i] = winfeatcorrel*px[mink[k]] + (1.0 - winfeatcorrel)*lx[i]; ly[i] = winfeatcorrel*py[mink[k]] + (1.0 - winfeatcorrel)*ly[i]; deltalx[i] = (x - lx[i]) / ndx[mink[k]]; deltaly[i] = (y - ly[i]) / ndy[mink[k]]; angle[i] = deltaorient * next(seed); sigb[i] = sigcos * (1.0 + (next(seed) + 1.0) / 2.0 * sigcosvar); } feat = ((bomb == 0 || bomb == 5) ? 1.0 : 0.0); for (i = 0; i < nn; i++) { float ddx = (deltalx[i] * cos(-angle[i]) + deltaly[i] * sin(-angle[i])); float iddy = (-deltalx[i] * sin(-angle[i]) + deltaly[i] * cos(-angle[i])); float ddy = iddy / pow(2.0, feataniso); float dd2 = pow(pow(abs(ddx), normfeat) + pow(abs(ddy), normfeat), 1.0 / normfeat); if (normfeat > 2.0) dd2 = (normfeat - 2.0) * (abs(ddx) > abs(ddy) ? abs(ddx) : abs(ddy)) + (1.0 - (normfeat - 2.0)) * dd2; float ff = 0.5 + 0.5 * cos(M_PI * float(freq) * sqrt(ddx * ddx * courbure * courbure + ddy * ddy)); ff = pow(ff, 1.0f / (0.0001 + thickness)); float ddist = dd2 / (footprint / sigb[i]); float dwin = 1.0 - ddist; if (dwin < 0.0) dwin = 0.0; if (bomb == 1) { float val = (valb[i] < 0.0 ? -0.25 + 0.75 * valb[i] : 0.25 + 0.75 * valb[i]); feat += ff * val * exp(-ddist); //if (k == 0) printf("i=%d, dd2=%g, feat=%g\n", i, dd2, feat); } else if (bomb == 2) feat += ff * exp(-ddist); else if (bomb == 3) { //printf("cell %d: at %g,%g, coeff=%g, feat=%g, prior=%g, max=%g\n", k, px[mink[k]], py[mink[k]], coeff, feat, prior, pmax); // add contributions, except if bombing if (pmax < prior[i] && dwin > 0.0 && ff>0.5) { pmax = prior[i]; vv = 2.0*(ff - 0.5) * exp(-ddist); pointvalue = npointvalue; cellpointx = lx[i]; cellpointy = ly[i]; } } else if (bomb == 4) { float ww = ff* exp(-ddist); if (closestdist < ww) { vv = ww; closestdist = ww; //( 1.0 - dd2 / ( footprint ) ); pointvalue = npointvalue; cellpointx = lx[i]; cellpointy = ly[i]; } } else feat = 1.0f; } if (bomb == 1) feat = 0.5 * feat + 0.5; // normalization if (bomb == 2) feat /= float(Npmax / 2 > 0 ? Npmax / 2 : 1); // normalization // apply phase which should be 0.0 or PI/2 if (bomb != 0) feat = feat * cos(phase) * cos(phase) + (1.0 - feat) * sin(phase) * sin(phase); //if ( feat < 0.0 ) feat = 0.0; //float correl = 1.0 - sddno / (footprint); if (correl<0.0) correl = 0.0; //if ((1.0 - winfeatcorrel) >= correl) correl = 1.0; //else if ((1.0 - winfeatcorrel) < correl*0.8) correl = 0.0; //else correl = ((1.0 - winfeatcorrel) - correl*0.8) / (correl*0.2); //if ((bomb != 3 && bomb != 4) || winshape != 0) vv += coeff * (1.0 * (1.0 - correl) + correl * feat); //if ( (bomb !=3 && bomb!=4) || winshape != 0 ) vv += coeff * feat ; if (bomb != 3 && bomb != 4) { vv += (coeff1 + coeff2) * feat; } //if (k==0) printf("k=%d, coeff=%g, feat=%g, vv=%g\n", k, coeff, feat, vv); } if ((bomb != 3 && bomb != 4) && winshape == 0 && winsum > 0.0) vv /= winsum; //if ((bomb != 3 && bomb != 4) && winsum > 0.0) vv /= winsum; if (vv < 0.0) vv = 0.0; return vv; } }; //unsigned int hvNoise::seed=0; } #endif // _HV_NOISE_H_
49,517
C++
.h
1,167
39.217652
197
0.553266
ASTex-ICube/semiproctex
39
8
2
LGPL-2.1
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,961
PtModelLibrary.h
ASTex-ICube_semiproctex/PPTBF_Structures_Src/PtModel/PtModelLibrary.h
/* * Publication: Semi-Procedural Textures Using Point Process Texture Basis Functions * Authors: anonymous * * Code author: Pascal Guehl * * anonymous * anonymous */ /** * @version 1.0 */ #ifndef _PT_MODEL_LIBRARY_H_ #define _PT_MODEL_LIBRARY_H_ /****************************************************************************** ******************************* INCLUDE SECTION ****************************** ******************************************************************************/ // Project #include "PtModelConfig.h" /****************************************************************************** ************************* DEFINE AND CONSTANT SECTION ************************ ******************************************************************************/ /****************************************************************************** ***************************** TYPE DEFINITION ******************************** ******************************************************************************/ /****************************************************************************** ******************************** CLASS USED ********************************** ******************************************************************************/ /****************************************************************************** ****************************** CLASS DEFINITION ****************************** ******************************************************************************/ namespace Pt { class PTMODEL_EXPORT PtDataModelLibrary { /************************************************************************** ***************************** PUBLIC SECTION ***************************** **************************************************************************/ public: /******************************* INNER TYPES *******************************/ /******************************* ATTRIBUTES *******************************/ /******************************** METHODS *********************************/ /** * Main GsGraphics module initialization method */ static bool initialize( const char* const pWorkingDirectory ); /** * Main GsGraphics module finalization method */ static void finalize(); /************************************************************************** **************************** PROTECTED SECTION *************************** **************************************************************************/ protected: /******************************* INNER TYPES *******************************/ /******************************* ATTRIBUTES *******************************/ /******************************** METHODS *********************************/ /************************************************************************** ***************************** PRIVATE SECTION **************************** **************************************************************************/ private: /******************************* INNER TYPES *******************************/ /******************************* ATTRIBUTES *******************************/ /** * Flag telling whether or not the library is initialized */ static bool mIsInitialized; /******************************** METHODS *********************************/ }; } #endif // !_PT_MODEL_LIBRARY_H_
3,405
C++
.h
71
44.971831
84
0.215324
ASTex-ICube/semiproctex
39
8
2
LGPL-2.1
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,962
PtModelConfig.h
ASTex-ICube_semiproctex/PPTBF_Structures_Src/PtModel/PtModelConfig.h
/* * Publication: Semi-Procedural Textures Using Point Process Texture Basis Functions * Authors: anonymous * * Code author: Pascal Guehl * * anonymous * anonymous */ /** * @version 1.0 */ #ifndef _PT_MODEL_CONFIG_H_ #define _PT_MODEL_CONFIG_H_ /****************************************************************************** ******************************* INCLUDE SECTION ****************************** ******************************************************************************/ /****************************************************************************** ************************* DEFINE AND CONSTANT SECTION ************************ ******************************************************************************/ //*** GsGraphics Library // Static or dynamic link configuration #ifdef WIN32 # ifdef PTMODEL_MAKELIB // Create a static library. # define PTMODEL_EXPORT # define PTMODEL_TEMPLATE_EXPORT # elif defined PTMODEL_USELIB // Use a static library. # define PTMODEL_EXPORT # define PTMODEL_TEMPLATE_EXPORT # elif defined PTMODEL_MAKEDLL // Create a DLL library. # define PTMODEL_EXPORT __declspec(dllexport) # define PTMODEL_TEMPLATE_EXPORT # else // Use DLL library # define PTMODEL_EXPORT __declspec(dllimport) # define PTMODEL_TEMPLATE_EXPORT extern # endif #else # if defined(PTMODEL_MAKEDLL) || defined(PTMODEL_MAKELIB) # define PTMODEL_EXPORT # define PTMODEL_TEMPLATE_EXPORT # else # define PTMODEL_EXPORT # define PTMODEL_TEMPLATE_EXPORT extern # endif #endif // ---------------- GLM library Management ---------------- ///** // * To remove warnings at compilation with GLM deprecated functions // */ //#define GLM_FORCE_RADIANS #endif // !_PT_MODEL_CONFIG_H_
1,723
C++
.h
51
32.27451
84
0.550542
ASTex-ICube/semiproctex
39
8
2
LGPL-2.1
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,963
PtPPTBF.hpp
ASTex-ICube_semiproctex/PPTBF_Structures_Src/PtModel/PtPPTBF.hpp
/* * Publication: Semi-Procedural Textures Using Point Process Texture Basis Functions * Authors: anonymous * * Code author: Pascal Guehl * * anonymous * anonymous */ /** * @version 1.0 */ /****************************************************************************** ******************************* INCLUDE SECTION ****************************** ******************************************************************************/ /****************************************************************************** ***************************** METHOD DEFINITION ****************************** ******************************************************************************/ namespace Pt { inline const PtWindow* const PtPPTBF::getWindow() const { return mWindow; } inline const PtFeature* const PtPPTBF::getFeature() const { return mFeature; } inline const PtNoise* const PtPPTBF::getNoise() const { return mNoise; } /****************************************************************************** * PPTBF size ******************************************************************************/ inline int PtPPTBF::getWidth() const { return mWidth; } inline void PtPPTBF::setWidth( const int pValue ) { mWidth = pValue; } inline int PtPPTBF::getHeight() const { return mHeight; } inline void PtPPTBF::setHeight( const int pValue ) { mHeight = pValue; } /****************************************************************************** * Model Transform ******************************************************************************/ inline int PtPPTBF::getResolution() const { return mResolution; } inline void PtPPTBF::setResolution( const int pValue ) { mResolution = pValue; } inline float PtPPTBF::getShiftX() const { return mShiftX; } inline void PtPPTBF::setShiftX( const float pValue ) { mShiftX = pValue; } inline float PtPPTBF::getShiftY() const { return mShiftY; } inline void PtPPTBF::setShiftY( const float pValue ) { mShiftY = pValue; } inline float PtPPTBF::getAlpha() const { return mAlpha; } inline void PtPPTBF::setAlpha( const float pValue ) { mAlpha = pValue; } inline float PtPPTBF::getRescalex() const { return mRescalex; } inline void PtPPTBF::setRescalex( const float pValue ) { mRescalex = pValue; } /****************************************************************************** * Point process ******************************************************************************/ inline int PtPPTBF::getTilingType() const { return static_cast< int >( mTilingType ); } inline float PtPPTBF::getJittering() const { return mJittering; } inline float PtPPTBF::getCellSubdivisionProbability() const { return mCellSubdivisionProbability; } inline int PtPPTBF::getNbRelaxationIterations() const { return mNbRelaxationIterations; } inline void PtPPTBF::setTilingType( const int pValue ) { mTilingType = static_cast< tilingtype >( pValue ); } inline void PtPPTBF::setJittering( const float pValue ) { mJittering = pValue; } inline void PtPPTBF::setCellSubdivisionProbability( const float pValue ) { mCellSubdivisionProbability = pValue; } inline void PtPPTBF::setNbRelaxationIterations( const int pValue ) { mNbRelaxationIterations = pValue; } /****************************************************************************** * Window function ******************************************************************************/ inline void PtPPTBF::setCellularToGaussianWindowBlend( const float pValue ) { mCellularToGaussianWindowBlend = pValue; } // - cellular window inline float PtPPTBF::getRectangularToVoronoiShapeBlend() const { return mRectangularToVoronoiShapeBlend; } inline void PtPPTBF::setRectangularToVoronoiShapeBlend( const float pValue ) { mRectangularToVoronoiShapeBlend = pValue; } inline float PtPPTBF::getCellularWindowDecay() const { return mCellularWindowDecay; } inline void PtPPTBF::setCellularWindowDecay( const float pValue ) { mCellularWindowDecay = pValue; } inline float PtPPTBF::getCellularWindowNorm() const { return mCellularWindowNorm; } inline void PtPPTBF::setCellularWindowNorm( const float pValue ) { mCellularWindowNorm = pValue; } // - Gaussian window inline int PtPPTBF::getWindowShape() const { return mWindowShape; } inline void PtPPTBF::setWindowShape( const int pValue ) { mWindowShape = pValue; } inline float PtPPTBF::getWindowArity() const { return mWindowArity; } inline void PtPPTBF::setWindowArity( const float pValue ) { mWindowArity = pValue; } inline float PtPPTBF::getWindowLarp() const { return mWindowLarp; } inline void PtPPTBF::setWindowLarp( const float pValue ) { mWindowLarp = pValue; } inline float PtPPTBF::getWindowNorm() const { return mWindowNorm; } inline void PtPPTBF::setWindowNorm( const float pValue ) { mWindowNorm = pValue; } inline float PtPPTBF::getWindowSmooth() const { return mWindowSmooth; } inline void PtPPTBF::setWindowSmooth( const float pValue ) { mWindowSmooth = pValue; } inline float PtPPTBF::getWindowBlend() const { return mWindowBlend; } inline void PtPPTBF::setWindowBlend( const float pValue ) { mWindowBlend = pValue; } inline float PtPPTBF::getWindowSigwcell() const { return mWindowSigwcell; } inline void PtPPTBF::setWindowSigwcell( const float pValue ) { mWindowSigwcell = pValue; } inline void PtPPTBF::setGaussianWindowDecay( const float pValue ) { mGaussianWindowDecay = pValue; } inline void PtPPTBF::setGaussianWindowDecayJittering( const float pValue ) { mGaussianWindowDecayJittering = pValue; } /****************************************************************************** * Feature function ******************************************************************************/ inline int PtPPTBF::getMinNbGaborKernels() const { return mMinNbGaborKernels; } inline void PtPPTBF::setMinNbGaborKernels( const int pValue ) { mMinNbGaborKernels = pValue; } inline int PtPPTBF::getMaxNbGaborKernels() const { return mMaxNbGaborKernels; } inline void PtPPTBF::setMaxNbGaborKernels( const int pValue ) { mMaxNbGaborKernels = pValue; } inline float PtPPTBF::getFeatureNorm() const { return mFeatureNorm; } inline void PtPPTBF::setFeatureNorm( const float pValue ) { mFeatureNorm = pValue; } inline int PtPPTBF::getGaborStripesFrequency() const { return mGaborStripesFrequency; } inline void PtPPTBF::setGaborStripesFrequency( const int pValue ) { mGaborStripesFrequency = pValue; } inline float PtPPTBF::getGaborStripesCurvature() const { return mGaborStripesCurvature; } inline void PtPPTBF::setGaborStripesCurvature( const float pValue ) { mGaborStripesCurvature = pValue; } inline float PtPPTBF::getGaborStripesOrientation() const { return mGaborStripesOrientation; } inline void PtPPTBF::setGaborStripesOrientation( const float pValue ) { mGaborStripesOrientation = pValue; } inline float PtPPTBF::getGaborStripesThickness() const { return mGaborStripesThickness; } inline void PtPPTBF::setGaborStripesThickness( const float pValue ) { mGaborStripesThickness = pValue; } inline float PtPPTBF::getGaborDecay() const { return mGaborDecay; } inline void PtPPTBF::setGaborDecay( const float pValue ) { mGaborDecay = pValue; } inline float PtPPTBF::getGaborDecayJittering() const { return mGaborDecayJittering; } inline void PtPPTBF::setGaborDecayJittering( const float pValue ) { mGaborDecayJittering = pValue; } inline float PtPPTBF::getFeaturePhaseShift() const { return mFeaturePhaseShift; } inline void PtPPTBF::setFeaturePhaseShift( const float pValue ) { mFeaturePhaseShift = pValue; } inline int PtPPTBF::getBombingFlag() const { return mBombingFlag; } inline void PtPPTBF::setBombingFlag( const int pValue ) { mBombingFlag = pValue; } inline float PtPPTBF::getFeatureWinfeatcorrel() const { return mFeatureWinfeatcorrel; } inline void PtPPTBF::setFeatureWinfeatcorrel( const float pValue ) { mFeatureWinfeatcorrel = pValue; } inline float PtPPTBF::getFeatureAnisotropy() const { return mFeatureAnisotropy; } inline void PtPPTBF::setFeatureAnisotropy( const float pValue ) { mFeatureAnisotropy = pValue; } /****************************************************************************** * Deformation ******************************************************************************/ inline float PtPPTBF::getTurbulenceAmplitude0() const { return mTurbulenceAmplitude0; } inline void PtPPTBF::setTurbulenceAmplitude0( const float pValue ) { mTurbulenceAmplitude0 = pValue; } inline float PtPPTBF::getTurbulenceAmplitude1() const { return mTurbulenceAmplitude1; } inline void PtPPTBF::setTurbulenceAmplitude1( const float pValue ) { mTurbulenceAmplitude1 = pValue; } inline float PtPPTBF::getTurbulenceAmplitude2() const { return mTurbulenceAmplitude2; } inline void PtPPTBF::setTurbulenceAmplitude2( const float pValue ) { mTurbulenceAmplitude2 = pValue; } /****************************************************************************** * Recursivity ******************************************************************************/ inline void PtPPTBF::setRecursiveWindowSubdivisionProbability( const float pValue ) { mRecursiveWindowSubdivisionProbability = pValue; } inline void PtPPTBF::setRecursiveWindowSubdivisionScale( const float pValue ) { mRecursiveWindowSubdivisionScale = pValue; } } // namespace Pt
9,225
C++
.h
372
23.459677
84
0.674248
ASTex-ICube/semiproctex
39
8
2
LGPL-2.1
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false